Laure D
Laure D

Reputation: 887

search specific tuples in list and dictionaries

let's say I have a list like this

liste=[(0,1,45), (0,2,90), (0,3,60), (1,2,50), (1,3,20), (2,3,25)]

and another list like this : number_list=(0,2)

so now, i would like to have a dictionary (or a list) in which i have for each key, the list of my tuples of liste, these tuples containing the numbers in number_list

on my exemple, what i want is:

d= { '0' : [(0,1,45), (0,2,90), (0,3,60)], '1' : [(1,2,50), (2,3,25)] }

so far i have written this :

d={}
for x in range(len(number_list)):
        d[format(x)]=[item for item in liste if number_list[x] in item]
print d

but it won't work and i can't understand why ?!

Thank you

Upvotes: 0

Views: 24

Answers (1)

John Coleman
John Coleman

Reputation: 52008

You could use a dictionary comprehension:

>>> liste=[(0,1,45), (0,2,90), (0,3,60), (1,2,50), (1,3,20), (2,3,25)]
>>> number_list=(0,2)
>>> d = {str(x):[item for item in liste if x in item] for x in number_list}
>>> d
{'0': [(0, 1, 45), (0, 2, 90), (0, 3, 60)], '2': [(0, 2, 90), (1, 2, 50), (2, 3, 25)]}

Also -- note that the keys in a dictionary don't need to be strings. You could just use the numbers themselves as keys, which might be more natural.

Upvotes: 1

Related Questions