0

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
piyush
  • 71
  • 2
  • 7
  • 2
    Possible duplicate of [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) – Szymon Jan 14 '16 at 03:22

3 Answers3

1

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"]

Copperfield
  • 8,131
  • 3
  • 23
  • 29
0

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

m7mdbadawy
  • 920
  • 2
  • 13
  • 17
0

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()')
Amaury Medeiros
  • 2,093
  • 4
  • 26
  • 42