Tsallaka zuwa abun ciki
Justice Tech School

Dictionary Methods

keys(), values() and items() give views you can loop over. get() reads safely, setdefault() adds a default, update() merges another dict, pop() removes a key and del removes by key. Looping over items() gives key and value together.

Example
user = {"name": "Ada", "age": 21}
print(list(user.keys()))
print(list(user.values()))
for key, value in user.items():
    print(key, "->", value)
user.update({"city": "Lagos"})
print(user.pop("age"))
print(user)
print(user.get("phone", "none"))

Result

['name', 'age']
['Ada', 21]
name -> Ada
age -> 21
21
{'name': 'Ada', 'city': 'Lagos'}
none

Exercise

Loop over keys and values together.

for k, v in user.():
    pass

Quiz Test

Which method returns all the keys?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.