Home > other >  Creating dictionary for multiple dictionaries in Python
Creating dictionary for multiple dictionaries in Python

Time:04-26

Trying to create a dictionary that contains multiple dictionaries, so that I can add data to the data key to each dictionary later.

Code so far:

decisions = ['decision1', 'decision2','decision3']
id_number = ['a1','a2','a3']

for x, y in zip(decisions, id_number):
    decision = {"name": x, "ID": y, "data": pd.DataFrame()}
    globals()[x] = decision

So far, this just creates multiple dictionaries. But I want to be able to put it into one dictionary so that I can use a for loop and input data into the data key within each dictionary.

How would I go about doing this?

CodePudding user response:

it's a little confusing to understand your exact requirements but assuming you want to use the values from id_number as your keys in the top level dictionary you can do something like:

decisions = ['decision1', 'decision2','decision3']
id_number = ['a1','a2','a3']

main_dict = {}

for x, y in zip(decisions, id_number):
    decision = {"name": x, "ID": y, "data": pd.DataFrame()}
    main_dict[x] = decision

functionally this is almost the same as your code except it is not creating a bunch of variables in the global namespace.

if you wanted to trim this down you can do:

decisions = ['decision1', 'decision2','decision3']
id_number = ['a1','a2','a3']
main_dict = {x: {"name": x, "ID": y, "data": pd.DataFrame()} for x, y in zip(id_number, decisions)}
  • Related