A dictionary stores data as key-value pairs, like a real dictionary where a word (the key) leads to its meaning (the value). You use dictionaries to store records such as a student’s details, to count things, and to look up values quickly. This lesson explains how to create, read, change and loop through dictionaries, with output for every example.

Try every example in our online Python compiler.

 

What is a dictionary?

A dictionary is written with curly braces {}, and each item is a key: value pair. Keys must be unique and unchangeable (strings, numbers and tuples work). Values can be anything. In Python 3.7 and newer, a dictionary keeps the order in which items were added.

student = {'name': 'Asha', 'age': 20, 'course': 'BCA'}
print(student)
print(type(student))

Output:

{'name': 'Asha', 'age': 20, 'course': 'BCA'}
<class 'dict'>

Access values

Use the key inside square brackets, or use the get() method.

student = {'name': 'Asha', 'age': 20, 'course': 'BCA'}
print(student['name'])
print(student.get('age'))
print(student.get('city'))
print(student.get('city', 'Not found'))

Output:

Asha
20
None
Not found

With square brackets, a missing key raises a KeyError. get() returns None instead, or a default value that you give.

 

Add and change items

student = {'name': 'Asha', 'age': 20, 'course': 'BCA'}
student['age'] = 21
student['city'] = 'Pune'
print(student)

Output:

{'name': 'Asha', 'age': 21, 'course': 'BCA', 'city': 'Pune'}

If the key exists, its value is changed. If it does not exist, a new pair is added.

 

Remove items

student = {'name': 'Asha', 'age': 21, 'course': 'BCA', 'city': 'Pune'}

print(student.pop('city'))
print(student)

del student['course']
print(student)

Output:

Pune
{'name': 'Asha', 'age': 21, 'course': 'BCA'}
{'name': 'Asha', 'age': 21}

pop(key) removes the key and returns its value. del removes the key without returning anything. popitem() removes the last added pair, and clear() empties the dictionary.

 

keys(), values() and items()

d = {'a': 1, 'b': 2, 'c': 3}
print(d.keys())
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))

Output:

dict_keys(['a', 'b', 'c'])
['a', 'b', 'c']
[1, 2, 3]
[('a', 1), ('b', 2), ('c', 3)]

Loop through a dictionary

d = {'a': 1, 'b': 2}

for key in d:
    print(key)

for key, value in d.items():
    print(key, value)

Output:

a
b
a 1
b 2

Looping over a dictionary directly gives its keys. Use items() to get keys and values together.

 

Check if a key exists

d = {'a': 1, 'b': 2, 'c': 3}
print('a' in d)
print('z' in d)
print(len(d))

Output:

True
False
3

The in operator checks keys, not values. len() gives the number of pairs.

 

Nested dictionaries

A value can be another dictionary.

people = {
    'p1': {'name': 'Asha', 'age': 20},
    'p2': {'name': 'Ravi', 'age': 22}
}
print(people['p2']['name'])

Output:

Ravi

Merge dictionaries

update() adds the pairs of one dictionary to another. If a key exists in both, the value from the second dictionary wins.

d1 = {'a': 1}
d2 = {'b': 2, 'a': 9}
d1.update(d2)
print(d1)

Output:

{'a': 9, 'b': 2}

Dictionary comprehension

squares = {x: x * x for x in range(1, 6)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example: count words in a sentence

A dictionary is perfect for counting. This is one of the most common uses.

text = 'to be or not to be'
counts = {}

for word in text.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)

Output:

{'to': 2, 'be': 2, 'or': 1, 'not': 1}

For each word, counts.get(word, 0) returns the current count, or 0 if the word is new, and we add 1.

 

Common mistakes

1. Reading a key that does not exist.

print({'a': 1}['z'])
KeyError: 'z'

Use get(), or check with in first.

2. Using a list as a key. Keys must be unchangeable, so use a tuple instead of a list.

3. Expecting duplicate keys. A key appears only once. If you add the same key again, the old value is replaced.

 

Practice questions

  1. Create a dictionary with the keys ‘maths’, ‘science’ and ‘english’ and your marks.
  2. Print the subject with the highest marks.
  3. Print the average of the marks.
  4. Print the subjects in alphabetical order.

Answers

marks = {'maths': 80, 'science': 90, 'english': 70}
print(max(marks, key=marks.get))            # science
print(sum(marks.values()) / len(marks))     # 80.0
print(sorted(marks))                        # ['english', 'maths', 'science']

Summary

  • A dictionary stores key-value pairs in curly braces, with unique keys.
  • Use d[key] or d.get(key) to read, and d[key] = value to add or change.
  • Use pop(), del and clear() to remove items.
  • Use items() to loop through keys and values together.