Python ยท collections

Dictionary Methods

Update, remove, look up with defaults, copy and build dictionaries with their built-in methods.

update


          # update multiple items
          person = {"name": "Alice"}
          person.update({"age": 25, "city": "NYC"})
          # ans: {"name": "Alice", "age": 25, "city": "NYC"}
        

pop


          # remove and return value
          person = {"name": "Alice", "age": 25}
          age = person.pop("age")
          # ans: age is 25
          # ans: person is {"name": "Alice"}
        

popitem


          # remove and return last item
          person = {"name": "Alice", "age": 25}
          item = person.popitem()
          # ans: item is ("age", 25)
        

"Last" means the most recently inserted pair: dictionaries remember insertion order.

setdefault


          # get or set default
          person = {"name": "Alice"}
          age = person.setdefault("age", 0)
          # ans: age is 0
          # ans: person is {"name": "Alice", "age": 0}
        

clear


          # remove all items
          person = {"name": "Alice", "age": 25}
          person.clear()
          # ans: {}
        

copy


          # shallow copy
          person = {"name": "Alice"}
          person_copy = person.copy()
          # ans: person_copy is {"name": "Alice"}
        

A new dictionary: adding keys to one does not affect the other. (Exercise 7 shows the catch.)

fromkeys


          # create dict from keys
          keys = ["a", "b", "c"]
          d = dict.fromkeys(keys, 0)
          # ans: {"a": 0, "b": 0, "c": 0}
        

Exercises

Predict the result, then reveal it.

Exercise 1


        # update behavior?
        d = {"a": 1}
        d.update({"b": 2, "a": 10})
        # ans: {"a": 10, "b": 2}
      

Exercise 2


        # pop with default?
        d = {"a": 1}
        d.pop("b", 0)
        # ans: 0
      

Exercise 3


        # pop without default?
        d = {"a": 1}
        d.pop("b")
        # ans: KeyError
      

Exercise 4


        # setdefault existing key?
        d = {"a": 1}
        d.setdefault("a", 10)
        # ans: 1 (doesn't change existing)
      

Exercise 5


        # popitem on empty?
        d = {}
        d.popitem()
        # ans: KeyError
      

Exercise 6


        # fromkeys default?
        keys = ["a", "b"]
        d = dict.fromkeys(keys)
        # ans: {"a": None, "b": None}
      

Exercise 7


          # copy is shallow?
          d = {"a": [1, 2]}
          d2 = d.copy()
          d2["a"].append(3)
          # ans: d is {"a": [1, 2, 3]}
        
d {'a': } 1 2 3 one list object d2 {'a': } a new dict, same value

Exercise 8


        # clear return?
        d = {"a": 1}
        result = d.clear()
        # ans: result is None
        # ans: d is {}
      

Exercise 9


        # update from pairs?
        d = {"a": 1}
        d.update([("b", 2), ("c", 3)])
        # ans: {"a": 1, "b": 2, "c": 3}
      

Exercise 10


        # multiple setdefault?
        d = {}
        d.setdefault("a", []).append(1)
        d.setdefault("a", []).append(2)
        # ans: {"a": [1, 2]}
      

The first call stores a new empty list and returns it; the second finds that same list and returns it. A handy way to group values.

Remember

update

Adds or overwrites many pairs, from a dict or a list of pairs.

pop / popitem

Remove and return; a missing key (or an empty dict) raises KeyError unless pop has a default.

setdefault

Returns the value if the key exists, otherwise stores and returns the default.

clear / copy / fromkeys

clear returns None; copy is shallow; fromkeys defaults every value to None.