A dictionary in Python is an unordered collection of items with each item consisting of a key and a value, typically referred to as key:value pairs. In a dictionary, a key is unique and immutable, and the value is any data type and doesn’t need to be unique.
Basic dictionary syntax:
pythondict_example = {key1: value1, key2: value2} student = { "name": "Andrew", "age": 22, "major": "Computer Science"}
Creating Dictionaries
Dictionaries can be created in multiple ways in Python.
Using curly braces {}
to create a dictionary:
pythonstudent = { "name": "Andrew", "age": 22, "major": "Computer Science"}
Using the dict()
constructor to create a dictionary:
pythonstudent = dict(name="Andrew", age=22, major="Computer Science")
Creating an empty dictionary:
pythonempty_dict = {}
Creating a dictionary from a list of key-value tuples using the dict()
constructor:
pythonpairs = [("name", "Andrew"), ("age", 22), ("major", "Computer Science")] my_dict = dict(pairs)
Accessing Dictionary Elements
Dictionary elements can be accessed by their keys, or with the get()
method to avoid raising a KeyError
if the key doesn’t exist.
Accessing values of a dictionary by key:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} print(student["name"]) # Output: Andrew print(student["age"]) # Output: 22
Accessing values of a dictionary with the get()
method:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} print(student.get("major")) # Output: Computer Science
Modifying Dictionaries
Similar to lists, dictionaries are mutable, meaning the elements can be added, updated, or removed after its been created.
Adding a key-value pair to a dictionary:
pythonstudent = {"name": "Andrew", "age": 22} student["major"] = "Computer Science" print(student) # Output: student = {"name": "Andrew", "age": 22, "major": "Computer Science"}
Updating an existing key of a dictionary
pythonstudent = {"name": "Andrew", "age": 22} student["age"] = 30 print(student) # Output: student = {"name": "Andrew", "age": 30}
Remove and return the value of a specified key with the pop()
method:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} age = student.pop("age") print(age) # Output: 22 print(student) # Output: {"name": "Andrew", "major": "Computer Science"}
Remove and return the last inserted key-value pair as a tuple with the popitem()
method:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} last_item = student.popitem() print(last_item) # Output: ('major', 'Computer Science')
Delete a key-value pair with a specified key using the del
statement:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} del student["age"] print(student) # Output: student = {"name": "Andrew", "major": "Computer Science"}
Remove all elements from a dictionary with the clear()
method:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} student.clear() print(student) # Output: {}
Dictionary Operations
In Python there are several operations that allow you to analyze and manipulate data within dictionaries.
Checking for the existence of a key in a dictionary using the in
keyword:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} print("name" in student) # Output: True print("gpa" in student) # Output: False
Find the number of key-value pairs in a dictionary using the len()
function:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} print(len(student)) # Output: 3
Return the keys, values, and items of a dictionary with the key()
, values()
, and items()
methods:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} print(student.keys()) # Output: dict_keys(['name', 'age', 'major']) print(student.values()) # Output: dict_values(['Andrew', 22, 'Computer Science']) print(student.items()) # Output: dict_items([('name', 'Andrew'), ('age', 22), ('major', 'Computer Science')])
The items()
method returns a view object containing the dictionaries key-value pairs as tuples.
Looping Through Dictionaries:
Loops can be used to loop through a dictionaries keys, values, or key-value pairs.
Looping through the keys of a dictionary:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} for key in student: print(key, student[key]) # Output: # name Andrew # age 22 # major Computer Science
Looping through the values of a dictionary:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} for value in student.values(): print(value) # Output: # Andrew # 22 # Computer Science
Looping through the key-value pairs of a dictionary:
pythonstudent = {"name": "Andrew", "age": 22, "major": "Computer Science"} for key, value in student.items(): print(key, value) # Output: # name Andrew # age 22 # major Computer Science
Nested Dictionaries
Dictionaries can contain other dictionaries, lists, or any other data type as values. This allows you to create complex, nested data structures.
pythonstudents = { "Andrew": {"age": 22, "major": "Computer Science"}, "Jackie": {"age": 21, "major": "Supply Chain"} } print(students["Jackie"]["major"] # Output: Supply Chain
Advanced Dictionary Techniques
Python has several techniques for working with dictionaries.
To merge two dictionaries, use the update()
method:
pythondict1 = {"x": 1, "y": 2} dict2 = {"a": 3, "b": 4 } dict1.update(dict2) print(dict1) # Output: {'x': 1, 'y': 2, 'a': 3, 'b': 4}
To sort a dictionary by its keys or values, use the sorted()
method, which returns a sorted list of tuples and not a dictionary.
Sorting a dictionary by keys:
pythonmy_dict = {"b": 2, "a": 1, "c": 3} sorted_by_keys = dict(sorted(my_dict.items())) print(sorted_by_keys) # Output: {'a': 1, 'b': 2, 'c': 3}
Sorting a dictionary by values:
pythonmy_dict = {"b": 2, "a": 1, "c": 3} sorted_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1])) print(sorted_by_values) # Output: {'a': 1, 'b': 2, 'c': 3}
When To Use Dictionaries Vs. Other Data Structures
It is important to understand when to use a dictionary instead of another data structure like lists and tuples. Here are the key differences between dictionaries, lists, and tuples:
- Dictionaries: Use when you need to associate keys with values, and especially if you need fast lookups
- Lists: Use when you need an ordered collection of items that can you modify and where the order of the elements is important
- Tuples: Use when you need an unordered collection of items that should not change
- Sets: Use when you need an unordered collection of unique items.
Use the following links to learn more about each data structure in detail: Lists, Tuples, Sets.
Conclusion
Dictionaries are an incredibly powerful and flexible data structure in Python, and are ideal for mapping keys to values and organizing data. Use your new knowledge of dictionaries in Python to further build on your skills as a programmer.