简体   繁体   中英

Create variable number of dictionary with name taken from list in Python

I have a list which grows and shrinks in a for loop. The list looks like following :- . With every element inside list of list i want to associate it to a separate dictionary.

list123 = [[1010,0101],[0111,1000]]

In this case I want to create 4 dictionary with the following name

dict1010 = {}
dict0101 = {}
dict0111 = {}
dict1000 = {}

I tried following loop

for list1 in list123:
    for element in list1:
        dict + str(element) = dict()

This is the error i am getting

SyntaxError: can't assign to literal

You can uses globals() function to add names to global namespace like this

for list1 in list123:
    for element in list1:
        globals()["dict"+str(element)] = {}

this will add variables with the names you want as if you created them using dictx={} also numbers that begins with 0 won't convert well using str() so you should make your list a list of strings

First of all, I must say that you shouldn't do this. However, if you really want to, you can use exec .

If you really want to do this, you could use exec:

list123 = [[1010,0101],[0111,1000]]
for list1 in list123:
    for element in list1:
        var = 'dict' + str(element)
        exec(var + ' = dict()')

while you can dynamically create variables, unless there is an overwhelming need to do that use instead a dictionary of dictionary witch key is the name you want, like this

my_dicts=dict()
for list1 in list123:
    for element in list1:
        my_dicts["dict" + str(element)] = dict()

and to access one of them do for example my_dicts["dict1010"]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM