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.
* As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets {}, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
You can access the items of a dictionary by referring to its key name, inside square brackets.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
// Accessing the model
x = thisdict["model"]
print(x) // Mustang
// Changing the year
thisdict["year"] = 2018
print(thisdict["year"]) // 2018
Dictionaries have several useful built-in methods:
keys(): Returns a list of all the keys.values(): Returns a list of all the values.items(): Returns a list containing a tuple for each key value pair.You can easily add new key:value pairs by assigning a value to a new key. To remove items, you can use the pop() or del keywords.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
// Adding an item
thisdict["color"] = "red"
// Removing an item
thisdict.pop("model")
print(thisdict)
A dictionary can contain dictionaries, this is called nested dictionaries. They are very useful for storing complex data structures.
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
}
}
print(myfamily["child2"]["name"]) // Output: Tobias
How is data structured inside a Python dictionary?