A dictionary (dict) stores information as key: value pairs. Instead of accessing the data by its position, as in a list, you access it by its key: just as in a word dictionary you look up the word to find its meaning.
Creating a dictionary
person = {"name": "Ana", "age": 25, "city": "Madrid"}
empty = {}
print(person) # {'name': 'Ana', 'age': 25, 'city': 'Madrid'}
print(type(person)) # <class 'dict'>
print(len(person)) # 3
Each element is a key: value pair. Keys must be unique and of an immutable type (usually text or numbers). Values can be of any type, even lists or other dictionaries.
Accessing a value
You put the key between square brackets:
person = {"name": "Ana", "age": 25}
print(person["name"]) # Ana
print(person["age"]) # 25
If the key does not exist, Python raises a KeyError:
print(person["phone"])
# KeyError: 'phone'
get: access without risk
The get method returns None (or the default value you give it) if the key does not exist, instead of raising an error:
print(person.get("phone")) # None
print(person.get("phone", "no phone")) # no phone
print(person.get("name", "no name")) # Ana
Checking whether a key exists
With in you check whether a key is in the dictionary (not the values):
person = {"name": "Ana", "age": 25}
print("name" in person) # True
print("Ana" in person) # False: Ana is a value, not a key
print("phone" not in person) # True
Adding and modifying
It is done with the same syntax: if the key exists its value is changed, and if it does not exist it is created.
person = {"name": "Ana", "age": 25}
person["age"] = 26 # modifies
person["city"] = "Madrid" # adds
print(person) # {'name': 'Ana', 'age': 26, 'city': 'Madrid'}
Deleting
person = {"name": "Ana", "age": 26, "city": "Madrid"}
del person["city"] # removes the key
age = person.pop("age") # removes and returns the value
print(age) # 26
print(person) # {'name': 'Ana'}
del and pop also raise KeyError if the key does not exist. You can use person.pop("key", None) to avoid it.
A dictionary keeps insertion order
Since Python 3.7 the elements are kept in the order in which they were added. Even so, you do not access by position but by key.
Practice in Contact book.