Initialize List to a variable in a Dictionary inside a loop

Your code is not appending elements to the lists; you are instead replacing the list with single elements. To access values in your existing dictionaries, you must use indexing, not attribute lookups (item['name'], not item.name).

Use collections.defaultdict():

from collections import defaultdict

example_dictionary = defaultdict(list)
for item in root_values:
    example_dictionary[item['name']].append(item['value'])

defaultdict is a dict subclass that uses the __missing__ hook on dict to auto-materialize values if the key doesn’t yet exist in the mapping.

or use dict.setdefault():

example_dictionary = {}
for item in root_values:
    example_dictionary.setdefault(item['name'], []).append(item['value'])

Leave a Comment