Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered (from Python 3.7 onwards), changeable, and does not allow duplicate keys.
1. Create dictionary
Dictionaries are written with curly brackets {}, and have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary items are presented in key:value pairs, and can be referred to by using the key name. Duplicate keys are not allowed; if you specify the same key twice, the second value will overwrite the first.
2. Access items
You can access the items of a dictionary by referring to its key name, inside square brackets.
x = thisdict["model"] # "Mustang"
You can also use the get() method to achieve the same result. get() is safer because it returns None instead of throwing an error if the key does not exist.
x = thisdict.get("model")
Getting Keys, Values, and Items
keys(): Returns a list of all the keys.values(): Returns a list of all the values.items(): Returns a list of tuples containing each key-value pair.
keys = thisdict.keys()
values = thisdict.values()
items = thisdict.items()
3. Change values
You can change the value of a specific item by referring to its key name.
thisdict["year"] = 2018
You can also use the update() method to update the dictionary with items from a given argument (a dictionary or an iterable of key-value pairs).
thisdict.update({"year": 2020})
4. Add items
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
thisdict["color"] = "red"
You can also use the update() method here; if the key does not exist, it will be added.
5. Remove items
There are several methods to remove items from a dictionary:
pop(): Removes the item with the specified key name.thisdict.pop("model")popitem(): Removes the last inserted item.thisdict.popitem()del: Removes the item with the specified key name. It can also delete the dictionary completely.del thisdict["year"]clear(): Empties the dictionary.thisdict.clear()
6. Loop through dictionary
You can loop through a dictionary by using a for loop. When looping, the return value are the keys, but there are methods to return the values as well.
# Loop through keys
for x in thisdict:
print(x) # prints keys
# Loop through values
for x in thisdict.values():
print(x)
# Loop through both keys and values
for x, y in thisdict.items():
print(x, y)
7. Nested dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
}
}
print(myfamily["child2"]["name"]) # Tobias
8. Dictionary methods
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 |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
Discussion
Loading comments...