Dynamic Dictionary of dictionaries Python -


i wanted create dictionary of dictionaries in python:

suppose have list contains keys:

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

suppose have data field numeric values (20 of them)

i want define dictionary stores 4 different dictionaries given corresponding value

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

so basically, should 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 best way achieve this?

use list comprehension , dict(zip(keys,value)) return dict you.

>>> keys = ['a', 'b', 'c', 'd', 'e'] >>> value = [1, 2, 3, 4, 5] >>> dictionary = [dict(zip(keys,value)) _ in xrange(4)] >>> 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 want dict of dicts use dict comprehension:

>>> keys = ['a', 'b', 'c', 'd', 'e'] >>> value = [1, 2, 3, 4, 5] >>> dictionary = {i: dict(zip(keys,value)) 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}} 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -