You can use a dictionary comprehension (supported in Python 2.7+):
>>> animals = ["dog", "cat", "cow"]
>>> {x: {} for x in animals}
{'dog': {}, 'cow': {}, 'cat': {}}
Answer from Eugene Yarmash on Stack OverflowYou can use a dictionary comprehension (supported in Python 2.7+):
>>> animals = ["dog", "cat", "cow"]
>>> {x: {} for x in animals}
{'dog': {}, 'cow': {}, 'cat': {}}
You may also use collections.defaultdict
primer_pos = defaultdict(dict)
Then whenever you reference primer_pos with a new key, a dictionary will be created automatically
primer_pos['cat']['Fluffy'] = 'Nice kitty'
Will by chain create {'Fluffy': 'Nice Kitty'} as value of key 'cat' in dictionary primer_pos
python - Initializing a dictionnary with a for loop - Stack Overflow
python - Initialize List to a variable in a Dictionary inside a loop - Stack Overflow
Adding Key: Value to Empty Dictionary via For Loop
How to append to dictionary within a for loop
Videos
I am working on a Python program to analyze hockey data and am trying to build it in such a way that I can add additional parameters to analyze later on. I thought that a for loop would be a good way to do this:
seasons = ['current', 'last']
event_types = ['shot', 'goal']
league_data = {}
for season in seasons:
for event in event_types:
league_data[season][event] = {}
league_data[season][event]['x'] = []
league_data[season][event]['y'] = []When I run the code I get a KeyError (KeyError: 'current'). Is it possible to initialize dictionaries using for loops? Or should I simply declare all of the dictionaries explicitly and save myself the headache?
EDIT:
I think I've figured it out. I looped through and created the league_data[season] entries first and then added the event entries in a separate 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'])
List and dictionary comprehensions can help here ...
Given
In [72]: root_values
Out[72]:
[{'name': 'red', 'value': 2},
{'name': 'red', 'value': 3},
{'name': 'red', 'value': 2},
{'name': 'green', 'value': 7},
{'name': 'green', 'value': 8},
{'name': 'green', 'value': 9},
{'name': 'blue', 'value': 4},
{'name': 'blue', 'value': 4},
{'name': 'blue', 'value': 4}]
A function like item() shown below can extract values with specific names:
In [75]: def item(x): return [m['value'] for m in root_values if m['name']==x]
In [76]: item('red')
Out[76]: [2, 3, 2]
Then, its just a matter of dictionary comprehension ...
In [77]: {x:item(x) for x in ['red', 'green', 'blue'] }
Out[77]: {'blue': [4, 4, 4], 'green': [7, 8, 9], 'red': [2, 3, 2]}