Python Tutorial · Data Structures · Lesson 18 of 42
Python Dictionaries
Key-value pairs: create, read safely, update, loop and nest dictionaries.
Creating dictionaries
A dictionary maps keys to values. Keys must be unique and immutable (strings, numbers, tuples).
user = {"name": "Ada", "age": 36, "langs": ["Python", "SQL"]}
print(user["name"])
user["age"] = 37
user["city"] = "London"
del user["langs"]
print(user)
print(len(user))
Output
Ada
{'name': 'Ada', 'age': 37, 'city': 'London'}
3Reading values safely
d[key] raises KeyError when the key is missing; d.get(key, default) returns a default instead.
config = {"debug": True}
print(config.get("debug"))
print(config.get("timeout", 30))
print("timeout" in config)
Output
True 30 False
Looping
prices = {"apple": 1.2, "pear": 0.9, "kiwi": 2.5}
for fruit, price in prices.items():
print(f"{fruit}: {price}")
print(list(prices.keys()))
cheap = {k: v for k, v in prices.items() if v < 2}
print(cheap)
Output
apple: 1.2
pear: 0.9
kiwi: 2.5
['apple', 'pear', 'kiwi']
{'apple': 1.2, 'pear': 0.9}Counting and grouping
Dictionaries are perfect for counting. collections.Counter and defaultdict make it even shorter:
from collections import Counter, defaultdict
words = "the cat and the hat and the bat".split()
print(Counter(words).most_common(2))
by_letter = defaultdict(list)
for w in words:
by_letter[w[0]].append(w)
print(dict(by_letter))
Output
[('the', 3), ('and', 2)]
{'t': ['the', 'the', 'the'], 'c': ['cat'], 'a': ['and', 'and'], 'h': ['hat'], 'b': ['bat']}Test yourself
What does {"a": 1}.get("b", 0) return?
NoneKeyError0"b"
Show answer
Answer: 0
Practice next
- Group Anagrams · coding problem
- Top K Frequent Elements · coding problem