having trouble populating a nested dictionary and retaining previously populated keys. see this example:
fulldict={}
keys=['key1', 'key2', 'key3']
for key in keys:
for i in xrange(3):
x1 = np.random.randn(10)
y1 = np.random.randn(10)
fulldict[key] = {i:pd.DataFrame({'x1':x1, 'y1': y1})}
my intent is that fulldict['key1']
should contain 3 dictionaries with keys 0,1,2. but only the last key (2) is stored.
any suggestions appreciated
You are reassigning the fulldict[key]
each time, so initialize fulldict[key] = {}
and use i
as a key:
for key in keys:
fulldict[key] = {}
for i in xrange(3):
x1 = np.random.randn(10)
y1 = np.random.randn(10)
fulldict[key][i] = pd.DataFrame({'x1':x1, 'y1': y1})
Or you could resort to a dict comprehension for the inner dict (saves a few lookups):
import numpy as np
fulldict={}
keys=['key1', 'key2', 'key3']
draw = np.random.randn
for key in keys:
fulldict[key] = {i: pd.DataFrame({'x1': draw(10), 'y1': draw(10)})
for i in xrange(3)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.