Alina
Alina

Reputation: 2261

pythonic way of initialization of dict in a for loop

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

Answers (3)

Munish
Munish

Reputation: 11

hash = {data: True for data in ['a', 'b', 'c']}
print(hash)

Output: {'a': True, 'b': True, 'c': True}

Upvotes: -1

volcano
volcano

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

Eugene Yarmash
Eugene Yarmash

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

Related Questions