0

I need to create a list of dictionaries:

box1 = {'x' : 10, 'y' : 10, 'direction' : 'right'}
box2 = {'x' : 20, 'y' : 10, 'direction' : 'right'}
box3 = {'x' : 30, 'y' : 10, 'direction' : 'right'}
box4 = {'x' : 40, 'y' : 10, 'direction' : 'right'}
box5 = {'x' : 50, 'y' : 10, 'direction' : 'right'}
box6 = {'x' : 60, 'y' : 10, 'direction' : 'right'}
box7 = {'x' : 70, 'y' : 10, 'direction' : 'right'}
box8 = {'x' : 80, 'y' : 10, 'direction' : 'right'}
box9 = {'x' : 90, 'y' : 10, 'direction' : 'right'}

I succeeded to create only one first dictionaty box1 using loop

for i in range(9):
    new_n = 'box' + str(i+1)
    exec(new_n + " = {}")

Can I use looping and exec method to create such a list? If not, how can I create it?

P.S.: I couldn't find an idea of a list comprehension which fills a list with dictionaries and assigns different names to those dictionaries. That's why this question is different from any others on this web site.

Alex F
  • 57
  • 5

1 Answers1

1
boxes = {"box%d"%i:{'x' : x, 'y' : 10, 'direction' : 'right'} for i,x in enumerate(range(10,91,10),1)}

print boxes["box1"]

my_var = "box1"
print boxes[my_var]

is probably how i would do it

in general you should avoid eval/exec

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Thank you! I appreciate your concise and smart code a lot! I got it. But as a result I get strings as names of dictionaries inside the list boxes. Could you tell me, please, how I can have names of those dictionaries as variables instead of strings? – Alex F Sep 29 '16 at 17:09
  • you dont want to do that ... use the variable name to index into the dictionary... – Joran Beasley Sep 29 '16 at 17:13
  • Opps. Sorry. I got the answer. Dictionaries always have string key names. Sorry for stupid quiestion. – Alex F Sep 29 '16 at 17:13
  • well they could have other things than strings as keys... but they have to be hashable items – Joran Beasley Sep 29 '16 at 17:14