andandandand
andandandand

Reputation: 22270

GIven a set of strings, create a dictionary of dictionaries using them as keys to entries with default values

I have this:

set_of_strings = {'abc', 'def', 'xyz'}

And I want to create this:

dict_of_dicts = {
     'abc': {'pr': 0, 'wt': 0},
     'def' : {'pr': 0, 'wt': 0},
     'xyz' : {'pr': 0, 'wt': 0} 
}

What's the pythonic way? (Python 2.7)

Upvotes: 2

Views: 66

Answers (3)

shx2
shx2

Reputation: 64328

As the other answers show, there are several ways to achieve this, but IMO the most (only?) pythonic way is using a dict comprehension:

keys = ...
{ k: { 'pr': 0, 'wt': 0 } for k in keys }

If the values were immutable, dict.fromkeys is good, and is probably faster than dict comprehension.

Upvotes: 2

falsetru
falsetru

Reputation: 369304

You can also use dict.fromkeys:

>>> d = dict.fromkeys({'abc', 'def', 'xyz'}, {'pr': 0, 'wt': 0})
>>> d
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}

NOTE:

The value specified ({'pr': 0, 'wt': 0}) is shared by all keys.

>>> d['xyz']['py'] = 1
>>> d
{'xyz': {'pr': 0, 'py': 1, 'wt': 0}, 'abc': {'pr': 0, 'py': 1, 'wt': 0}, 'def': {'pr': 0, 'py': 1, 'wt': 0}}

Upvotes: 2

TerryA
TerryA

Reputation: 60004

Like this?

>>> set_of_strings = {'abc', 'def', 'xyz'}
>>> dict_of_dicts = {}
>>> for key in set_of_strings:
...     dict_of_dicts[key] = {'pr':0, 'wt':0}
... 
>>> print dict_of_dicts
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}

As a dictionary comprehension:

>>> {k:{'pr':0, 'wt':0} for k in {'abc', 'def', 'xyz'}}
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}

Alternatively, you can do something like:

>>> set_of_strings = {'abc', 'def', 'xyz'}
>>> value = {'pr': 0, 'wt': 0} 
>>> dict(zip(set_of_strings, [value]*len(set_of_strings)))
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}

Upvotes: 3

Related Questions