Dictionary
What is it
Dictionaries are used to store data values in key:value pairs.
dict = { "brand": "Ford", "model": "Mustang", "year": 1964 }
Values can be referred using the dict[key] or the .get() method.
dict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(dict["brand"]) # Ford # .get() method can also be used item = dict.get("model") # Mustang
Mutating Dictionary Entries
Setting key to value.
dictionary[key] = value
Deleting a key:value pair.
- Raises KeyErrorifkeyis not in the dictionary.
del dictionary[key]
Index Reference, Sort Order, and Duplicate Entries
Dictionaries are unordered.
Dictionary items CAN'T be referenced by an index.
Duplicate value assignment of a same key will override existing entries.
In below example, setting year key twice will take the latter value of 2020 over earlier assigned valued of 1964.
dict = { "brand": "Ford", "model": "Mustang", "year": 1964, "year": 2020 } print(dict) # { # 'brand': 'Ford', # 'model': 'Mustang', # 'year': 2020 # }