Dict methods
- Python course
- Beginner
- Lesson 68/116
- 4 min
Learn get, keys, values, items methods.
Dict methods
Common dict methods are keys(), values(), items():
person = {"name": "Alex", "age": 28}
print(list(person.keys())) # ['name', 'age']
print(list(person.values())) # ['Alex', 28]
print(list(person.items())) # [('name', 'Alex'), ('age', 28)]These methods are handy for looping over a dict. With items() you get the key and value together.
get, pop, update
Other common dict methods are get(key, default), pop(key), update(other):
person = {"name": "Alex"}
print(person.get("age", 0)) # 0
person.pop("name") # returns "Alex", removes it
person.update({"age": 28}) # adds a new keyget returns a default instead of KeyError. pop removes a key and returns its value. update merges another dict.
Practice Print dict keys and values
Assign the dict {"name": "Ayse", "age": 28} to person. Assign list(person.keys()) to keys and list(person.values()) to values. Then print print(keys, values).
Starter code
# List the dict partsSample solution
person = {"name": "Ayse", "age": 28}
keys = list(person.keys())
values = list(person.values())
print(keys, values)Expected output
['name', 'age'] ['Ayse', 28]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the methods
| Term | Meaning |
|---|---|
keys() |
Keys |
values() |
Values |
items() |
Pairs |
get() |
Safe access |
2 Complete the get call
person = {"name": "Alex"}
age = person.____("age", 0)
person = {"name": "Alex"}
age = person.get("age", 0)
Explanation: get("age", 0) returns 0 for a missing key.
3 What does person.get("age", 0) return (person = {"name": "Alex"})?
- Raises KeyError
- 0 Correct answer
- None
- 28
Explanation: 'age' is missing, so the default 0 is returned.