
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an item by using an index.
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
Dictionaries cannot have two items with the same key:
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)To determine how many items a dictionary has, use the len() function:
Print the number of items in the dictionary:
print(len(thisdict))
The values in dictionary items can be of any data type:
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["gray"9 "white", "blue"]
}From Python's perspective, dictionaries are defined as objects with the data type 'dict':
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))It is also possible to use the dict() constructor to make a dictionary.
Using the dict() method to make a dictionary:
thisdict = dict(name = "John", age = 36, country = "Norway") print(thisdict)
There are four collection data types in the Python programming language:
You can access the items of a dictionary by referring to its key name, inside square brackets:
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]There is also a method called get() that will give you the same result:
x = thisdict.get("model")The keys() method will return a list of all the keys in the dictionary.
x = thisdict.keys()
The values() method will return a list of all the values in the dictionary.
x = thisdict.values()
The items() method will return each item in a dictionary, as tuples in a list.
x = thisdict.items()
To determine if a specified key is present in a dictionary use the in keyword:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")You can change the value of a specific item by referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018The update() method will update the dictionary with the items from the given argument.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})Adding an item to the dictionary is done by using a new index key and assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "gray"9np font-boldrint(thisdict)The update() method will update the dictionary with items from a given argument. If the item does not exist, the item will be added.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "gray"9)There are several methods to remove items from a dictionary:
pop() methodthisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)popitem() methodRemoves the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict.popitem() print(thisdict)
del keyworddel thisdict["model"] print(thisdict)
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.clear() methodThe clear() method empties the dictionary:
thisdict.clear() print(thisdict)
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Print all key names in the dictionary, one by one:
for x in thisdict: print(x)
Print all values in the dictionary, one by one:
for x in thisdict: print(thisdict[x])
You can also use the values() method to return values of a dictionary:
for x in thisdict.values(): print(x)
You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys(): print(x)
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items(): print(x, y)
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)Another way to make a copy is to use the built-in function dict().
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)A dictionary can contain dictionaries, this is called nested dictionaries.
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary:
Print the name of child 2:
print(myfamily["child2"]["name"])
You can loop through a dictionary by using the items() method like this:
Loop through the keys and values of all nested dictionaries:
for x, obj in myfamily.items():
print(x)
for y in obj:
print(y + ':', obj[y])Python has a set of built-in methods that you can use on dictionaries.
| Method | Description |
|---|---|
| clear() | Removes all the elements from the dictionary |
| copy() | Returns a copy of the dictionary |
| fromkeys() | Returns a dictionary with the specified keys and value |
| get() | Returns the value of the specified key |
| items() | Returns a list containing a tuple for each key value pair |
| keys() | Returns a list containing the dictionary's keys |
| pop() | Removes the element with the specified key |
| popitem() | Removes the last inserted key-value pair |
| setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
| update() | Updates the dictionary with the specified key-value pairs |
| values() | Returns a list of all the values in the dictionary |