Python Tutorial › Data Structures › Dictionaries

Python Dictionaries

BeginnerLesson 23 of 4713 min read10 runnable examples

A dictionary stores data as key-value pairs, so you can look a value up by a meaningful key instead of a position. Dictionaries model JSON, configuration, database rows and counters, which makes them one of the most used types in Python.

Advertisement
In this lesson
  • Create dictionaries and read values safely
  • Add, update and delete keys
  • Loop over keys, values and items
  • Work with nested dicts and merging

Create a dictionary

Write key: value pairs inside curly braces. Keys are usually strings, but any immutable value works.

Python
user = {"name": "Asha", "role": "tester", "years": 4}print(user)print(len(user)) ports = dict(http=80, https=443)       # dict() with keyword argumentsprint(ports)
Output
{'name': 'Asha', 'role': 'tester', 'years': 4}
3
{'http': 80, 'https': 443}

Since Python 3.7, dictionaries keep the order in which keys were inserted.

Read values

Use square brackets with the key. A missing key raises KeyError, so use get() when a key may be absent.

Python
user = {"name": "Asha", "role": "tester"}print(user["name"])print(user.get("email"))                    # None instead of an errorprint(user.get("email", "not provided"))    # with a defaultprint("role" in user)                       # checks keys
Output
Asha
None
not provided
True
Python
user = {"name": "Asha"}print(user["email"])
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(user["email"])
          ~~~~^^^^^^^^^
KeyError: 'email'
Advertisement

Add, change and delete

Python
config = {"browser": "chromium", "headless": True} config["timeout"] = 30          # add a new keyconfig["browser"] = "firefox"   # replace an existing valueconfig.update({"retries": 2, "headless": False})print(config) removed = config.pop("retries")  # remove and returndel config["timeout"]           # removeprint(removed, config)
Output
{'browser': 'firefox', 'headless': False, 'timeout': 30, 'retries': 2}
2 {'browser': 'firefox', 'headless': False}

setdefault() returns a key’s value, adding it with a default first if it is missing:

Python
groups = {}for name, team in [("asha", "qa"), ("ravi", "dev"), ("meena", "qa")]:    groups.setdefault(team, []).append(name)print(groups)
Output
{'qa': ['asha', 'meena'], 'dev': ['ravi']}

Loop over a dictionary

Python
stock = {"pen": 40, "notebook": 0, "bag": 7} for item in stock:                  # keys    print(item, end=" ")print() print(list(stock.values())) for item, qty in stock.items():     # key and value together    if qty == 0:        print(item, "is out of stock")
Output
pen notebook bag 
[40, 0, 7]
notebook is out of stock

Count things with a dict

Counting is the classic dictionary job:

Python
text = "the quick brown fox jumps over the lazy dog the end"counts = {}for word in text.split():    counts[word] = counts.get(word, 0) + 1 print(counts["the"])top = max(counts, key=counts.get)print(top, counts[top])
Output
3
the 3
Tip

collections.Counter does this in one line: Counter(text.split()).most_common(1). See the Collections lesson.

Advertisement

Nested dictionaries

Values can be lists or other dictionaries, which is exactly the shape of JSON data.

Python
response = {    "status": 200,    "data": {        "user": {"id": 7, "name": "Ravi"},        "roles": ["admin", "tester"],    },}print(response["data"]["user"]["name"])print(response["data"]["roles"][-1])print(response.get("error", {}).get("message", "no error"))
Output
Ravi
tester
no error

Merge dictionaries

Python
defaults = {"browser": "chromium", "headless": True, "timeout": 30}overrides = {"headless": False} settings = defaults | overrides      # Python 3.9+print(settings)print({**defaults, **overrides} == settings)
Output
{'browser': 'chromium', 'headless': False, 'timeout': 30}
True

When both have the same key, the value from the right-hand dict wins.

Dictionary methods

MethodWhat it does
get(k, default)Value for k, or default if missing
keys(), values(), items()Views of the keys, values or pairs
update(other)Adds or replaces keys from another dict
pop(k)Removes k and returns its value
popitem()Removes and returns the last inserted pair
setdefault(k, d)Returns k‘s value, inserting d first if missing
copy()Shallow copy
clear()Removes everything
dict.fromkeys(keys, v)New dict with each key set to v

Sort a dictionary

Python
scores = {"Asha": 88, "Ravi": 74, "Meena": 93}print(sorted(scores))                                    # keysprint(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))ranked = dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))print(ranked)
Output
['Asha', 'Meena', 'Ravi']
[('Meena', 93), ('Asha', 88), ('Ravi', 74)]
{'Meena': 93, 'Asha': 88, 'Ravi': 74}
Advertisement

Check your understanding

Predict the output

d = {"a": 1, "b": 2}d["a"] += 10d.setdefault("c", 3)d.setdefault("a", 99)print(d, d.get("z", 0))

Quick quiz

1. What does d.get("x") return when “x” is not a key?

2. Which loop gives both keys and values?

3. Which of these can NOT be a dictionary key?

4. In a | b, if both dicts have key “x”, whose value is kept?

Exercise: invert a dictionary

Swap keys and values of a country-code dict, then look up the code for “India”.

Input
{"IN": "India", "US": "United States", "JP": "Japan"}
Expected output
{'India': 'IN', 'United States': 'US', 'Japan': 'JP'}
IN
Hint 1

A dict comprehension: {v: k for k, v in codes.items()}.

Program Practice

Advertisement

Python dictionary FAQ

Are Python dictionaries ordered?

Yes. Since Python 3.7, dictionaries preserve insertion order.

How do I check if a key exists in a dictionary?

Use in: if "email" in user:. Use get() when you also want the value.

How do I merge two dictionaries in Python?

Use a | b (Python 3.9+) or {a, b} to create a new dict, or a.update(b) to change a in place.

What is the difference between dict.get() and dict[key]?

dict[key] raises KeyError if the key is missing. dict.get(key) returns None or a default instead.