3

i have following list: parent_child_list with id-tuples:

[(960, 965), (960, 988), (359, 364), (359, 365), 
(361, 366), (361, 367), (361, 368), (361, 369), 
(360, 370), (360, 371), (360, 372), (360, 373), (361, 374)]

Example: i would like to print those values which are combined with the id 960. Those would be: 965, 988

I tried to convert the list into a dict:

rs = dict(parent_child_list)

Because now i could simply say:

print rs[960]

But unfortunately i forgot that dict cannot have double values so instead of getting 965, 988 as the answer i receive only 965.

Is there any easy option to keep the double values?

Many thanks

Constantine
  • 193
  • 1
  • 3
  • 11

5 Answers5

5

You can use defaultdict to create dictionary with list as its value type, then append values.

from collections import defaultdict
l = [(960, 965), (960, 988), (359, 364), (359, 365), (361, 366), (361, 367), (361, 368), (361, 369), (360, 370), (360, 371), (360, 372), (360, 373), (361, 374)]

d = defaultdict(list)

for key, value in l:
    d[key].append(value)
vittt
  • 96
  • 4
1

You can use a list comprehension to build a list, using if to filter out matching ids:

>>> parent_child_list = [(960, 965), (960, 988), (359, 364), (359, 365)]
>>> [child for parent, child in parent_child_list if parent == 960]
[965, 988]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

You can always iterate:

parent_child_list = [(960, 965), (960, 988), (359, 364), (359, 365),
(361, 366), (361, 367), (361, 368), (361, 369),
(360, 370), (360, 371), (360, 372), (360, 373), (361, 374)]

for key, val in parent_child_list:
    if key == 960:
        print str(val)
Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
0

The list comprehension

[y for (x, y) in parent_child_list if x == 960]

will give you a list of y values for tuples whose x values equal 960.

jgloves
  • 719
  • 4
  • 14
0

You have been given the way to extract individual using a list comprehension or loop but you can construct the dictionary you desire for all values:

>>> d = {}
>>> for parent, child in parent_child_list:
...     d.setdefault(parent, []).append(child)
>>> d[960]
[965, 988]

Alternative to using a raw python dict, you could use a collections.defaultdict(list) and just directly append, e.g. d[parent].append(child)

AChampion
  • 29,683
  • 4
  • 59
  • 75