Skip to content Skip to sidebar Skip to footer

Append To A Nested List Or Dict In Python

I often find myself populating lists and dicts by reading in files line by line. Let's say I'm reading in a list of people and their favourite foods: ANNE CHEESE ANNE P

Solution 1:

The better way is to use a defaultdict:

>>>from collections import defaultdict>>>d = defaultdict(list)>>>d["hello"].append(1)>>>d["hello"].append(2)>>>dict(d)
{'hello':[1, 2]}

Solution 2:

If all your values are lists, then you can use the defaultdict. Otherwise you can get similar behaviour by chaining setdefault and append:

a = {}
for key,value in [("k1","v1"), ("k1","v2")]:
    a.setdefault(key,[]).append(value)

Post a Comment for "Append To A Nested List Or Dict In Python"