Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split array of dictionaries in Python?

[{50: 2, 75: 3, 99: 4}, {50: 5, 75: 6, 99: 7}, {50: 8, 75: 9, 99:10}] 

The following is an array of dictionaries in Python. I want to convert the array into following three arrays in Python:

[2, 5, 8] # corresponding to 50.
[3, 6, 9] # corresponding to 75.
[4, 7, 9] # corresponding to 99. 
like image 778
JavaDeveloper Avatar asked Jun 09 '26 09:06

JavaDeveloper


1 Answers

One way may be to use defaultdict such that it is dictionary with values of list corresponding to keys:

from collections import defaultdict

my_list = [{50: 2, 75: 3, 99: 4}, {50: 5, 75: 6, 99: 7}, {50: 8, 75: 9, 99:10}] 
my_dict_list = defaultdict(list)

for value in my_list:
    for k,v in value.items():
        my_dict_list[k].append(v)

And the list of values for each can be accessed by keys as below:

print(my_dict_list[50])
like image 109
student Avatar answered Jun 11 '26 22:06

student



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!