ZetCode

Python dictionary

last modified November 29, 2026 Python 3.15

In this article we show how to work with dictionaries in Python.

A dictionary is a mutable collection of key-value pairs. Each key is unique and maps to one value. Keys must be hashable, for example strings, numbers, or tuples; values can be anything. Dictionaries look up a value by its key in constant time on average, and since Python 3.7 they keep the insertion order of their keys.

The many ways to create a dictionary, including dict, zip, fromkeys, comprehensions, merging, and copying, are covered in Python create dictionary. Here we work with dictionaries that already exist.

Accessing values

The square brackets return the value of a key. The get method does the same but returns a default value when the key is missing.

access.py
capitals = {'Slovakia': 'Bratislava', 'Hungary': 'Budapest',
            'Poland': 'Warsaw'}

print(capitals['Hungary'])
print(len(capitals))

print(capitals.get('Poland'))
print(capitals.get('Austria'))
print(capitals.get('Austria', 'unknown'))

try:
    print(capitals['Austria'])
except KeyError as e:
    print('missing key:', e)

The len function returns the number of pairs. Without a second argument, get returns None for a missing key. The brackets raise a KeyError instead. We use brackets when the key must exist and get when a missing key is a normal case.

$ python access.py
Budapest
3
Warsaw
None
unknown
missing key: 'Austria'

Adding and changing pairs

Assigning to a key adds a new pair or replaces the value of an existing one. The update method and the |= operator copy many pairs at once.

change.py
basket = {'oranges': 12, 'pears': 5}

basket['apples'] = 4
basket['pears'] = 8
basket['oranges'] += 3
print(basket)

basket.update({'pears': 10, 'kiwis': 6})
basket.update(plums=2)
print(basket)

extra = {'apples': 1, 'lemons': 7}
print(basket | extra)

basket |= extra
print(basket)

The += operator reads the value of oranges and stores the new one. The update method accepts another dictionary or keyword arguments; existing keys get new values, new keys are appended at the end. The | operator returns a new merged dictionary, while |= changes basket in place. In both cases, the value from the right operand wins, so apples becomes 1.

$ python change.py
{'oranges': 15, 'pears': 8, 'apples': 4}
{'oranges': 15, 'pears': 10, 'apples': 4, 'kiwis': 6, 'plums': 2}
{'oranges': 15, 'pears': 10, 'apples': 1, 'kiwis': 6, 'plums': 2, 'lemons': 7}
{'oranges': 15, 'pears': 10, 'apples': 1, 'kiwis': 6, 'plums': 2, 'lemons': 7}

Counting and grouping

Two common tasks need a default value for keys that are not yet in the dictionary: counting and grouping. The get and setdefault methods handle them without an if statement.

counting.py
text = '''the falcon flew over the hill and the falcon
saw a hare near the hill'''

counts = {}

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

print(counts)
print(counts['the'], counts['falcon'])

by_letter = {}

for word in sorted(set(text.split())):
    by_letter.setdefault(word[0], []).append(word)

print(by_letter)

To count words, we read the current count with get(word, 0) and store the count plus one. The setdefault method returns the value of a key; if the key is missing, it first inserts the given default. Here it returns the list of words for a letter, creating an empty list the first time, and we append to it. The collections module offers Counter and defaultdict for the same tasks.

$ python counting.py
{'the': 4, 'falcon': 2, 'flew': 1, 'over': 1, 'hill': 2, 'and': 1, 'saw': 1, 'a': 1, 'hare': 1, 'near': 1}
4 2
{'a': ['a', 'and'], 'f': ['falcon', 'flew'], 'h': ['hare', 'hill'], 'n': ['near'], 'o': ['over'], 's': ['saw'], 't': ['the']}

Removing items

The pop method removes a key and returns its value, popitem removes the last inserted pair, the del statement deletes a key, and clear removes everything.

remove.py
stock = {'pens': 12, 'pads': 4, 'ink': 3, 'clips': 50, 'tape': 2}

n = stock.pop('pads')
print(n, stock)

print(stock.pop('cups', 0))

item = stock.popitem()
print(item, stock)

del stock['ink']
print(stock)

try:
    del stock['ink']
except KeyError as e:
    print('no such key:', e)

stock.clear()
print(stock, len(stock))

With a second argument, pop returns it for a missing key instead of raising KeyError. The popitem method works in LIFO order: it returns the pair added last, here ('tape', 2). Deleting a missing key with del raises KeyError.

$ python remove.py
4 {'pens': 12, 'ink': 3, 'clips': 50, 'tape': 2}
0
('tape', 2) {'pens': 12, 'ink': 3, 'clips': 50}
{'pens': 12, 'clips': 50}
no such key: 'ink'
{} 0

Dictionary views

The keys, values, and items methods return view objects. A view does not copy the data; it shows the current content of the dictionary.

views.py
prices = {'bread': 2.1, 'milk': 1.3, 'eggs': 3.2}

keys = prices.keys()
values = prices.values()
items = prices.items()

print(keys)
print(values)
print(items)

prices['butter'] = 2.8
del prices['milk']

print(keys)
print(list(values))
print(len(items))

shop = {'bread': 2.0, 'butter': 2.9, 'apples': 1.8}
print(sorted(prices.keys() & shop.keys()))
print(sorted(prices.keys() - shop.keys()))
print(sorted(prices.keys() | shop.keys()))

After we add butter and delete milk, the views created earlier show the change. Key views behave like sets, so the &, -, and | operators find the common keys, the keys only in prices, and all keys. The results are sets, which have no fixed order, so we sort them before printing.

$ python views.py
dict_keys(['bread', 'milk', 'eggs'])
dict_values([2.1, 1.3, 3.2])
dict_items([('bread', 2.1), ('milk', 1.3), ('eggs', 3.2)])
dict_keys(['bread', 'eggs', 'butter'])
[2.1, 3.2, 2.8]
3
['bread', 'butter']
['eggs']
['apples', 'bread', 'butter', 'eggs']

Looping over a dictionary

A for loop over a dictionary goes over its keys. To get the keys and values together, we loop over items.

looping.py
scores = {'Alice': 82, 'Bob': 67, 'Carol': 91, 'Dave': 74}

for name in scores:
    print(name, end=' ')
print()

for name, score in scores.items():
    print(f'{name:6} {score:3} {"pass" if score >= 70 else "fail"}')

total = 0
for score in scores.values():
    total += score

print(f'average: {total / len(scores):.2f}')

for i, (name, score) in enumerate(scores.items(), start=1):
    print(f'{i}. {name}')

The items method yields key-value tuples, which we unpack into two variables. The values method is enough when we do not need the keys. With enumerate, each tuple is unpacked inside another tuple, so the loop variables are written as i, (name, score).

$ python looping.py
Alice Bob Carol Dave 
Alice   82 pass
Bob     67 fail
Carol   91 pass
Dave    74 pass
average: 78.50
1. Alice
2. Bob
3. Carol
4. Dave

Membership testing

The in and not in operators test whether a key is in a dictionary. To test values, we use the values view.

membership.py
users = {'jdoe': 'John Doe', 'rroe': 'Roger Roe', 'lsmith': 'Lucia Smith'}

print('jdoe' in users)
print('John Doe' in users)
print('John Doe' in users.values())
print('tnovak' not in users)
print(('rroe', 'Roger Roe') in users.items())

for login in ['lsmith', 'tnovak']:
    if login in users:
        print(f'{login}: {users[login]}')
    else:
        print(f'{login}: no such user')

The test 'John Doe' in users is False, because in looks only at keys. A key test is fast, while a test on values goes through all values one by one. The items view can test a whole pair.

$ python membership.py
True
False
True
True
True
lsmith: Lucia Smith
tnovak: no such user

Insertion order

A dictionary keeps its keys in the order in which they were first inserted. Changing a value does not move the key.

order.py
steps = {}
steps['download'] = 'done'
steps['unpack'] = 'done'
steps['build'] = 'running'
print(list(steps))

steps['unpack'] = 'redo'
print(list(steps))

steps['unpack'] = steps.pop('unpack')
print(list(steps))

a = {'x': 1, 'y': 2}
b = {'y': 2, 'x': 1}
print(a == b)
print(list(a.items()) == list(b.items()))
print(list(reversed(steps)))

To move a key to the end, we pop it and insert it again. Two dictionaries with the same pairs are equal even if their order differs; to compare the order as well, we compare the lists of items. The reversed function goes over the keys from the last to the first.

$ python order.py
['download', 'unpack', 'build']
['download', 'unpack', 'build']
['download', 'build', 'unpack']
True
False
['unpack', 'build', 'download']

Sorting a dictionary

A dictionary has no sort method. We use the sorted function, which returns a list, and build a new dictionary from it if needed.

sorting.py
population = {'Bratislava': 475_503, 'Vilnius': 607_404,
              'Lisbon': 567_131, 'Riga': 605_802, 'Helsinki': 674_500,
              'Budapest': 1_686_222, 'Prague': 1_397_880}

print(sorted(population))

by_name = dict(sorted(population.items()))
print(list(by_name)[:3])


def by_count(item):
    return item[1]


for city, n in sorted(population.items(), key=by_count, reverse=True):
    print(f'{city:10} {n:>9,}')

top3 = sorted(population, key=population.get, reverse=True)[:3]
print(top3)
print(max(population, key=population.get))

Sorting a dictionary sorts its keys. Sorting items sorts the pairs by key, and dict turns the result back into a dictionary. To sort by value, we pass a key function that returns the second element of each pair. When we only need the keys ordered by their values, the bound method population.get serves as the key function. More options are shown in Python sort list.

$ python sorting.py
['Bratislava', 'Budapest', 'Helsinki', 'Lisbon', 'Prague', 'Riga', 'Vilnius']
['Bratislava', 'Budapest', 'Helsinki']
Budapest   1,686,222
Prague     1,397,880
Helsinki     674,500
Vilnius      607,404
Riga         605,802
Lisbon       567,131
Bratislava   475,503
['Budapest', 'Prague', 'Helsinki']
Budapest

Changing a dictionary while looping

A dictionary must not change its size while we loop over it. Changing the values of existing keys is allowed.

mutate.py
stock = {'pens': 12, 'pads': 0, 'ink': 3, 'clips': 0}

try:
    for item in stock:
        if stock[item] == 0:
            del stock[item]
except RuntimeError as e:
    print('error:', e)

print(stock)

for item in list(stock):
    if stock[item] == 0:
        del stock[item]

print(stock)

stock = {'pens': 12, 'pads': 0, 'ink': 3, 'clips': 0}
in_stock = {k: v for k, v in stock.items() if v > 0}
print(in_stock)

for item in stock:
    stock[item] += 10
print(stock)

The first loop deletes pads, and the next step of the loop raises a RuntimeError; clips is not removed. The fix is to loop over a copy of the keys with list(stock), or to build a new dictionary with a comprehension. The last loop only changes values, so it is safe.

$ python mutate.py
error: dictionary changed size during iteration
{'pens': 12, 'ink': 3, 'clips': 0}
{'pens': 12, 'ink': 3}
{'pens': 12, 'ink': 3}
{'pens': 22, 'pads': 10, 'ink': 13, 'clips': 10}

Nested dictionaries

The values of a dictionary can be dictionaries. Such nested dictionaries are common for configuration and JSON data.

nested.py
config = {
    'server': {'host': 'localhost', 'port': 8080},
    'database': {'name': 'shop', 'user': 'admin',
                 'pool': {'min': 2, 'max': 10}},
}

print(config['server']['port'])
print(config['database']['pool']['max'])

config['database']['pool']['max'] = 20
config.setdefault('logging', {})['level'] = 'info'

print(config.get('cache', {}).get('ttl', 300))

for section, options in config.items():
    print(f'[{section}]')
    for key, value in options.items():
        print(f'  {key} = {value}')

Each pair of brackets goes one level deeper. The setdefault method creates the logging section if it does not exist and returns it, so we can set a key in it on the same line. Chained get calls with an empty dictionary as the default read an optional value without a KeyError.

$ python nested.py
8080
10
300
[server]
  host = localhost
  port = 8080
[database]
  name = shop
  user = admin
  pool = {'min': 2, 'max': 20}
[logging]
  level = info

Inverting a dictionary

To look up keys by value, we build an inverted dictionary that maps the values back to the keys.

invert.py
codes = {'SK': 'Slovakia', 'CZ': 'Czechia', 'AT': 'Austria'}

names = {v: k for k, v in codes.items()}
print(names)
print(names['Austria'])

languages = {'Slovakia': 'Slovak', 'Czechia': 'Czech',
             'Austria': 'German', 'Germany': 'German',
             'Switzerland': 'German'}

print({v: k for k, v in languages.items()})

speakers = {}
for country, lang in languages.items():
    speakers.setdefault(lang, []).append(country)

print(speakers)

A comprehension inverts the dictionary when the values are unique. When they are not, later pairs overwrite earlier ones: only Switzerland is left for German. To keep all keys, we group them in lists with setdefault.

$ python invert.py
{'Slovakia': 'SK', 'Czechia': 'CZ', 'Austria': 'AT'}
AT
{'Slovak': 'Slovakia', 'Czech': 'Czechia', 'German': 'Switzerland'}
{'Slovak': ['Slovakia'], 'Czech': ['Czechia'], 'German': ['Austria', 'Germany', 'Switzerland']}

Source

Mapping types – dict – Python documentation

Dictionaries – Python tutorial

In this article we have accessed, changed, removed, looped over, and sorted the items of Python dictionaries. See also Python create dictionary, Python set, Python collections, and Python dict builtin.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.