Reputation: 2261
Is there a python way of initialization of a dictionary?
animals = ["dog","cat","cow"]
for x in animals:
primers_pos[x]={}
Is there something like
(primers_pos[x]={} for x in animals)
Upvotes: 3
Views: 12860
Reputation: 11
hash = {data: True for data in ['a', 'b', 'c']}
print(hash)
Output: {'a': True, 'b': True, 'c': True}
Upvotes: -1
Reputation: 3582
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
Upvotes: 1
Reputation: 149806
You can use a dictionary comprehension (supported in Python 2.7+):
>>> animals = ["dog", "cat", "cow"]
>>> {x: {} for x in animals}
{'dog': {}, 'cow': {}, 'cat': {}}
Upvotes: 8