Skip to content Skip to sidebar Skip to footer

Converting Dict Values That Are List Of Varying Lengths Into One List

I have data that was given as a list of dictionaries. The values of the dictionaries are list of int values of varying lengths. [{'values': [876.0]}, {'values': [823.0]}, {'value

Solution 1:

You can use list comprehension.

rr_intervals = [val for sub_dict in rr_list for val in sub_dict['values']] #rr_list is the list of dictionaries.
# [876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]

Solution 2:

You can use list comprehension to achieve that in a pythonic way,

L = [{'values': [876.0]},
     {'values': [823.0]},
     {'values': [828.0]},
     {'values': [838.0]},
     {'values': [779.0]},
     {'values': [804.0, 805.0, 738.0]},
     {'values': [756.0]},
     {'values': [772.0]},
     {'values': [802.0]},
     {'values': [812.0]},
     {'values': [746.0]},
     {'values': [772.0]},
     {'values': [834.0, 844.0]}]

values = [num for d in L for key, value in d.items() for num in value]
print(values)

Output:

[876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]

Solution 3:

Not sure if it's "elegant":

result = []

for i in rr_list:
    result += i.get('values')

Output:

[876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]

Solution 4:

You could try:

rr_intervals = []
for dictionary in rr_list:
    for value in dictionary.values():
        rr_intervals.extend(value)

Post a Comment for "Converting Dict Values That Are List Of Varying Lengths Into One List"