Python Dictionaries
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable, and does not allow duplicates.
Note: As of Python 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Creating a Dictionary
Dictionaries are written with curly brackets, and have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets.
x = thisdict["model"]
There is also a method called get() that will give you the same result:
x = thisdict.get("model")
Modifying Dictionaries
Change Values
You can change the value of a specific item by referring to its key name.
thisdict["year"] = 2018
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"
Remove Items
The pop() method removes the item with the specified key name.
thisdict.pop("model")
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
# Print all key names
for x in thisdict:
print(x)
# Print all values
for x in thisdict:
print(thisdict[x])
# Loop through both keys and values
for key, value in thisdict.items():
print(key, value)