Deltos Deltos - 2 months ago 5
Python Question

How to create a list of dictionaries?

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.

Answer
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

Comments