Changing and Adding Values
The values in a dictionary can change. You assign a new value to a key the same way as to a variable, with =:
player = {"name": "Ninja", "level": 1, "lives": 3}
player["level"] = 2
print(player){'name': 'Ninja', 'level': 2, 'lives': 3}You can also calculate the new value from the old one, as with variables: player["lives"] = player["lives"] - 1, or shorter, player["lives"] -= 1.
Note the difference: when you create a dictionary, you write a pair inside the curly braces with a colon ("level": 1). When you change a value later, you use square brackets and = (player["level"] = 2).
If you assign to a key that the dictionary doesn't have yet, Python adds a new pair at the end:
player = {"name": "Ninja", "level": 1, "lives": 3}
player["weapon"] = "sword"
print(player){'name': 'Ninja', 'level': 1, 'lives': 3, 'weapon': 'sword'}Each key can be in a dictionary only once. When you assign to a key that is already there, Python doesn't add a second pair with the same key; it replaces the value. That's handy, but it also means that nothing warns you about a typo: player["Level"] = 2 doesn't change "level". It adds a new key, "Level", and Ninja stays at level 1.
You can also start with an empty dictionary, {}, and add pairs to it one by one. And len(), which you know from lists and text, tells you how many pairs a dictionary has:
player = {}
player["name"] = "Ninja"
player["level"] = 1
print(player)
print(len(player)){'name': 'Ninja', 'level': 1}
2To remove a pair, use .pop() with its key, as you use it with an index in a list: player.pop("level") removes the pair with the key "level" and returns its value.
Instructions
- 1
Ninja has finished the first level. At the end of the program, increase the value of
"level"by 1 and printplayeragain. The second line should be{'name': 'Ninja', 'level': 2, 'lives': 3}. - 2
Ninja has found a sword. At the end of the program, add the key
"weapon"with the value"sword"to the dictionary and printplayeronce more. - 3
Finally, use
len()to print how many pairsplayerhas now. The last line should be4.