[{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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With