dawg
dawg

Reputation: 1

Dynamic Dictionary of dictionaries Python

I wanted to create a dictionary of dictionaries in Python:

Suppose I already have a list which contains the keys:

keys = ['a', 'b', 'c', 'd', 'e']
value = [1, 2, 3, 4, 5]

Suppose I have a data field with numeric values (20 of them)

I want to define a dictionary which stores 4 different dictionaries with the given to a corresponding value

for i in range(0, 3)
   for j in range(0, 4)
     dictionary[i] = { 'keys[j]' : value[j] }

So basically, it should be like:

dictionary[0] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5}
dictionary[1] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5}
dictionary[2] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5}
dictionary[3] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5}

What is the best way to achieve this?

Upvotes: 0

Views: 980

Answers (3)

Phil Cooper
Phil Cooper

Reputation: 5877

for a list of dictionaries:

dictionary = [dict(zip(keys,value)) for i in xrange(4)]

If you really wanted a dictionary of dictionaries like you said:

dictionary = dict((i,dict(zip(keys,value))) for i in xrange(4))

I suppose you could use pop or other dict calls which you could not from a list

BTW: if this is really a data/number crunching application, I'd suggest moving on to numpy and/or pandas as great modules.

Edit re: OP comments, if you want indicies for the type of data you are talking about:

# dict keys must be tuples and not lists
[(i,j) for i in xrange(4) for j in range(3)]
# same can come from itertools.product
from itertools import product
list(product(xrange4, xrange 3))

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

Use a list comprehension and dict(zip(keys,value)) will return the dict for you.

>>> keys = ['a', 'b', 'c', 'd', 'e']
>>> value = [1, 2, 3, 4, 5]
>>> dictionary = [dict(zip(keys,value)) for _ in xrange(4)]
>>> from pprint import pprint
>>> pprint(dictionary)
[{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]

If you want a dict of dicts then use a dict comprehension:

>>> keys = ['a', 'b', 'c', 'd', 'e']
>>> value = [1, 2, 3, 4, 5]
>>> dictionary = {i: dict(zip(keys,value)) for i in xrange(4)}
>>> pprint(dictionary)
{0: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 1: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 2: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 3: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}}

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142146

An alternative that only zips once...:

from itertools import repeat
map(dict, repeat(zip(keys,values), 4))

Or, maybe, just use dict.copyand construct the dict once:

[d.copy() for d in repeat(dict(zip(keys, values)), 4)]

Upvotes: 1

Related Questions