Python Dictionary: a quick reference

The dictionary doesn’t guarantee the order of the elements and is mutable.

One important characteristic of dictionaries is that you can set your customized access keys for each element.

Initialization of a Dictionary

Empty Dictionary

people = {}

Dictionary with initial values

people = {'Bob':30, 'Mary':25}

Adding in a Dictionary

If the key doesn’t exist yet, it is appended to the dictionary.

people['Sarah']=32

Updating a Dictionary

If the key already exists, the value is just updated.

#Bob's age is 28 now
people['Bob']=28

Notice that the code is pretty much the same.

Deleting in a Dictionary

To remove Bob from the dictionary:

people.pop('Bob')

To delete everybody:

people.clear()

Retrieving in a Dictionary

bob_age = people['Bob']
print(bob_age)
30

Iterating over Dictionaries

To print the keys:

for person in people:
  print(person)
Bob
Mary

To print the values, in our example, ages:

for person in people:
  print(people[person])
30
25

Check if a given key already exists in a Dictionary

if 'Bob' in people:
  print('Bob exists!')
else:
  print('There is no Bob!')