This Dictionary Methods lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
keys, values, and items are views of the pairs. update copies pairs in from another dict. pop removes one key and returns its value.
A view is not a list. Wrap it in list when you need a fixed copy.
Example 1: Start here
update overwrites a key that already exists.
learner = {"name": "Meera"} # a dictionary; each key has one value
learner.update({"city": "Chennai"}) # copy those keys into this dictionary
print(list(learner.items()))
Example 2: Keys, values, items
keys and values give you the two sides of the dictionary.
learner = {"name": "Asha", "score": 82} # a dictionary; each key has one value
print(list(learner.keys()))
print(list(learner.values()))
Example 3: Loop the pairs
items yields the key and the value together.
learner = {"name": "Asha", "score": 82} # a dictionary; each key has one value
for key, value in learner.items(): # repeat the indented lines once per value
print(key, value) # a comma prints each value, with a space between
Example 4: Remove a key
pop removes the key and returns the value that was stored there.
learner = {"name": "Asha", "score": 82} # a dictionary; each key has one value
print(learner.pop("score"))
print(learner)
