0

I'm sure i'm doing something silly, but I'm trying to take a list of dictionaries and make a dictionary where one of the key:value pairs in the dictionary becomes a key and the remaining key:value pairs become part of the value where the value is a list of dictionaries. An example is here:

In [115]: aa = ['a', 'b', 'c', 'd']

In [116]: my_dict = dict.fromkeys(key_list, [])

In [143]: my_dict
Out[143]: {'a': [], 'b': [], 'c': [], 'd': []}

In [117]: list_of_dicts = [{'letter':'a', 'val1':2, 'val2':3}, {'letter':'b', 'val1':4, 'val2':5}, {'letter':'c', 'val1':6, 'val2':7}]

In [118]: %paste
for entry in list_of_dicts:
    remainder = {k:v for k, v in entry.iteritems() if k!='letter'}
    my_dict[entry['letter']].append(remainder)

## -- End pasted text --

In [119]: my_dict
Out[119]: 
{'a': [{'val1': 2, 'val2': 3}, {'val1': 4, 'val2': 5}, {'val1': 6, 'val2': 7}],
 'b': [{'val1': 2, 'val2': 3}, {'val1': 4, 'val2': 5}, {'val1': 6, 'val2': 7}],
 'c': [{'val1': 2, 'val2': 3}, {'val1': 4, 'val2': 5}, {'val1': 6, 'val2': 7}],
 'd': [{'val1': 2, 'val2': 3}, {'val1': 4, 'val2': 5}, {'val1': 6, 'val2': 7}]}

Why are my values being applied to every entry in the dictionary?

Why isnt' the final dictionary:

In [121]: final_dict
Out[121]: 
{'a': [{'val1': 2, 'val2': 3}],
 'b': [{'val1': 4, 'val2': 5}],
 'c': [{'val1': 6, 'val2': 7}]}
gus
  • 395
  • 4
  • 16

1 Answers1

3

my_dict = dict.fromkeys(key_list, []) uses the same list for all the keys

You can use

my_dict = {k: [] for k in key_list}

to get a new list for each key

alternatively, you can use collections.defaultdict

my_dict = defaultdict(list)

which calls list() to make a new list every time you insert a new key

John La Rooy
  • 295,403
  • 53
  • 369
  • 502