cwse cwse - 4 months ago 13
Python Question

Python Update Dictionary values to reference dataframes with the same name

I have many dataframes with names such as 'ABC', 'XYZ'...

I also have a dictionary with keys, where each key has a list of 200 values which are the names of the dataframes i.e. ['ABC','XYZ',...]

I want to update this dictionary, so instead of containing the names of the dataframes, it contains the dataframes themselves as a nested dictionary.

THis will enable me to iterate over a specific key of the main dictionary dictionary, and access each of its 200 dataframes by name

i.e. dictionary[key1][ABC] would print out the ABC dataframe.

Any ideas? :)


Easy enough, use eval:

u, v, w, x, y, z = 1, 2, 3, 4, 5, 6
frames = {}
names = {'a' : ['u', 'v'],
         'b' : ['w', 'x'],
         'c' : ['y', 'z']}
for key in names:
    frames[key] = dict(zip(names[key], [eval(name) for name in names[key]]))
# Output:
{'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}