Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Merging dictionary lists

I have lists inside a dictionary:

Number_of_lists=3           #user sets this value, can be any positive integer
My_list={}
for j in range(1,Number_of_lists+1):
  My_list[j]=[(x,y,z)]  

The Number_of_lists is a variable set by the user. Without knowing beforehand the value set by the user, i would like to finally have a merged list of all dictionary lists. For example if Number_of_lists=3 and the corresponding lists are My_list[1]=[(1,2,3)] , My_list[2]=[(4,5,6)] , My_list[3]=[(7,8,9)] the result would be:

All_my_lists=My_list[1]+My_list[2]+My_list[3]

where: All_my_lists=[(1,2,3),(4,5,6),(7,8,9)].

So what i'm trying to do is automate the above procedure for all possible:

Number_of_lists=n #where n can be any positive integer

I'm a bit lost up to now trying to use an iterator to add the lists up and always fail. I'm a python beginner and this is a hobby of mine, so if you answer please explain everything in your answer i'm doing this to learn, i'm not asking from you to do my homework :)

EDIT

@codebox (look at the comments below) correctly pointed out that My_List as displayed in my code is in fact a dictionary and not a list. Be careful if you use any of the code.

like image 992
CosmoSurreal Avatar asked Oct 07 '22 22:10

CosmoSurreal


1 Answers

use a list comprehension:

>>> Number_of_lists=3 
>>> My_list={}
>>> for j in range(1,Number_of_lists+1):
      My_list[j]=(j,j,j)
>>> All_my_lists=[My_list[x] for x in My_list]

>>> print(All_my_lists)
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

All_my_lists=[My_list[x] for x in My_list] is equivalent to:

All_my_lists=[]
for key in My_list:
   All_my_lists.append(My_list[key])
like image 141
Ashwini Chaudhary Avatar answered Oct 10 '22 02:10

Ashwini Chaudhary