JavaDeveloper
JavaDeveloper

Reputation: 5660

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. 

Upvotes: 2

Views: 3382

Answers (5)

vash_the_stampede
vash_the_stampede

Reputation: 4606

If your goal is 3 individual lists you could create each list with list comprehension

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

l_50 = [v for i in l for k, v in i.items() if k == 50] # => [2, 5, 8]
l_75 = [v for i in l for k, v in i.items() if k == 75] # => [3, 6, 9]
l_99 = [v for i in l for k, v in i.items() if k == 99] # => [4, 7, 10]

Or you can construct a dictionary and look up each list by key

d = {k: [j[x] for j in l for x in j if x == k] for i in l for k in i}
{50: [2, 5, 8], 75: [3, 6, 9], 99: [4, 7, 10]}

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55469

A Python dict is an unsorted collection, at least it is before Python 3.6, so you can't guarantee that the keys retain insertion order. And since you want the keys to be in numerical order we need to sort them.

Then we can use a list comprehension to extract the corresponding values from each dict in the list, and use tuple assignment to assign each of the list to a separate name.

data = [{50: 2, 75: 3, 99: 4}, {50: 5, 75: 6, 99: 7}, {50: 8, 75: 9, 99:10}]
a, b, c = [[d[k] for d in data] for k in sorted(data[0].keys())]

FWIW, it may be more convenient to save the output as a single list of lists, rather than as 3 separate lists.

Upvotes: 3

Alexander
Alexander

Reputation: 109526

Given that all dictionaries in your list will have the same keys, you can use a dictionary and list comprehension:

>>> {k: [d.get(k) for d in my_list_of_dicts] for k in my_list_of_dicts[0]}
{50: [2, 5, 8], 75: [3, 6, 9], 99: [4, 7, 10]}

Upvotes: 2

blhsing
blhsing

Reputation: 106465

Assuming your list is stored as l, you can use zip to transpose the dict values within:

list(zip(*(d.values() for d in l)))

This returns:

[(2, 5, 8), (3, 6, 9), (4, 7, 10)]

Upvotes: 2

niraj
niraj

Reputation: 18208

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

Upvotes: 5

Related Questions