Marielle Dado
Marielle Dado

Reputation: 147

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]},
 {'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]},

I would like to get all dict values into one list (named rr_intervals in my sample code).

[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]

My solution below worked just fine, but it took a while with all the nested for loops. I was wondering whether there'd be a more elegant solution?

rr_intervals = []
for dictionary in rr_list:
    for key in dictionary:
        if len(dictionary[key]) == 1:
            rr_intervals.append(dictionary[key][0])
        elif len(dictionary[key]) > 1:
            for rr in dictionary[key]:
                rr_intervals.append(rr)

Upvotes: 0

Views: 57

Answers (4)

Ch3steR
Ch3steR

Reputation: 20669

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]

Upvotes: 3

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 478

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]

Upvotes: 2

Shubham Sharma
Shubham Sharma

Reputation: 71687

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]

Upvotes: 3

FabZanna
FabZanna

Reputation: 201

You could try:

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

Upvotes: 1

Related Questions