Dict methods

The methods you will use most:

  • d.get(k, default) reads a key without risking KeyError.
  • d.setdefault(k, v) sets k only if it is missing, then returns its value.
  • d.pop(k) removes a key and returns its value.
  • d.update(other) copies keys in from another dict, overwriting.
  • d | other builds a new merged dict. On a clash, the right side wins.
  • d.keys(), d.values() and d.items() are live views of the dict.

One trap: you can't add or delete keys while looping over a dict. Python raises RuntimeError: dictionary changed size during iteration. Loop over a copy of the keys instead, with for k in list(d):. Changing the value of an existing key is fine.

Run it, then try stock.update(kiwi=2) to see that keyword arguments work too.