🎓 A1Learner
🔍

Python Dictionary Methods

Dictionary methods build, read, add, change, copy, and remove pairs in a dictionary. One new method, dict.fromkeys(), hides a sharing trap.

Build with fromkeys

Every key starts at 0. A number is safe here, because numbers do not change in place.

players = ["Ada", "Bob", "Cy"]
scores = dict.fromkeys(players, 0)
print(scores)

The fromkeys sharing trap

Both keys share the same list. Adding through one key shows under both keys.

groups = dict.fromkeys(["red", "blue"], [])
groups["red"].append("Ada")
print(groups)

setdefault adds a missing key

Bob is missing, so setdefault adds the pair. It also returns the new value.

scores = {"Ada": 10}
print(scores.setdefault("Bob", 0))
print(scores)

setdefault keeps an existing value

Ada is already there, so nothing changes. The call returns the old value.

scores = {"Ada": 10}
print(scores.setdefault("Ada", 99))
print(scores)

Copy a dictionary

The copy starts with the same pairs. Changing the copy leaves the original alone.

original = {"Ada": 10, "Bob": 8}
copy_scores = original.copy()
copy_scores["Ada"] = 20
print(original)
print(copy_scores)

Example

players = ["Ada", "Bob", "Cy", "Dee"]
board = {}
for name in players:
    board[name] = {"score": 0, "games": 0}
board["Ada"]["score"] = 5
for name, record in board.items():
    print(name, record["score"])

Key points

  • Use dict.fromkeys(keys, value) to build a dictionary with the same starting value for every key.
  • Use setdefault(key, default) to add a pair only when the key is missing.
  • setdefault() returns the value for the key after the call.
  • Use copy() to make a new dictionary with the same pairs.
  • Changing a top level pair in a copy does not change the original.
  • Recap: keys(), values() and items() give views of a dictionary.
  • Recap: get() reads safely.
  • Recap: update() adds or changes pairs.
  • Recap: pop() and popitem() remove pairs.
  • Recap: clear() empties a dictionary.
  • A change to a shared list value through one key shows under every key.
  • Each dictionary method does one job on the pairs in a dictionary.

In this example, players holds four names. The board starts empty. Each loop round makes a fresh inner dictionary with score 0 and games 0. It stores that dictionary under the player name. Ada then gets a score of 5. Only Ada changes, because each player has a separate inner dictionary. The last loop prints each name with its score.

Note

dict.fromkeys() shares one value object for all keys.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

groups = dict.fromkeys(["red", "blue"], []) and then groups["red"].append("Ada"). What is groups["blue"]?