-1

I have a set of tuples within a list in which I am trying to group the similar items together. Eg.

[('/Desktop/material_design_segment/arc_01.texture', 'freshnel_intensity_3.0022.jpg'),
 ('/Desktop/material_design_segment/arc_01.texture', 'freshnel_intensity_4.0009.jpg'),
 ('/Desktop/material_design_segment/arc_08.texture', 'freshnel_intensity_8.0020.jpg'),
 ('/Desktop/material_design_segment/arc_05.texture', 'freshnel_intensity_5.0009.jpg'),
 ('/Desktop/material_design_filters/custom/phase_03.texture', 'rounded_viscosity.0002.jpg'),
 ('/Desktop/material_design_filters/custom/phase_03.texture', 'freshnel_intensity_9.0019.jpg')]

My results should return me:

'/Desktop/material_design_segment/arc_01.texture':
    'freshnel_intensity_3.0022.jpg',
    'freshnel_intensity_4.0009.jpg',
'/Desktop/material_design_segment/arc_08.texture':
    'freshnel_intensity_8.0020.jpg'
'/Desktop/material_design_segment/arc_05.texture':
    'freshnel_intensity_5.0009.jpg'
'/Desktop/material_design_filters/custom/phase_03.texture':
    'rounded_viscosity.0002.jpg',
    'freshnel_intensity_9.0019.jpg'

However, when I tried using my code as follows, it only returns me 1 item.

groups = defaultdict(str)
for date, value in aaa:
    groups[date] = value

pprint(groups)

This is the ouput:

{'/Desktop/material_design_segment/arc_01.texture': 'freshnel_intensity_4.0009.jpg'
 '/Desktop/material_design_filters/custom/phase_03.texture': 'freshnel_intensity_9.0019.jpg'
 '/Desktop/material_design_segment/arc_08.texture': 'freshnel_intensity_8.0020.jpg'
 '/Desktop/material_design_segment/arc_05.texture': 'freshnel_intensity_5.0009.jpg'}

Where am I doing it wrong?

yan
  • 631
  • 9
  • 30

2 Answers2

1

You're assigning value to groups[date], which overwrites the previous value. You need to append it to a list.

groups = defaultdict(list)
for date, value in aaa:
    groups[date].append(value)
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
0

You should append the values into a list as follows (based on your code):

groups = defaultdict(list)
for date, value in aaa:
    groups[date].append(value)

print(groups)
Laurent H.
  • 6,316
  • 1
  • 18
  • 40