user7249622
user7249622

Reputation: 115

make a matrix from a list of dictionaries in python3

I have a list of dictionaries like this example:

example:

a = [{'C': 3742, 'A': 38799, 'F': 66, 'D': 848, 'B': 12953, 'E': 140}, {'C': 2319, 'A': 23551, 'F': 33, 'D': 568, 'B': 8192, 'E': 87}]

for every single dictionary in the list I would like to sort the items based on the the Keys from A to F. and then make a list of lists (of the sorted dictionary) but only from the values of dictionary. here is the expected output:

expected output:

res = [[38799, 12953, 3742, 848, 140, 66], [23551, 8192, 2319, 568, 87, 33]]

to do so I made the following code in python:

res = []
for i in range(len(a)):
    for e in sorted(a[i].keys()):
        res.append(a[i][e])

but it does not return what I want. do you know how to fix it?

Upvotes: 1

Views: 279

Answers (5)

Nouman
Nouman

Reputation: 7303

Here is another method using the function items of dict:

>>> [[i[1] for i in sorted(e.items())] for e in a]
[[38799, 12953, 3742, 848, 140, 66], [23551, 8192, 2319, 568, 87, 33]]
>>> 

It sorts the values by keys.

Upvotes: 0

Olvin Roght
Olvin Roght

Reputation: 7812

To sort items you can use built-in function sorted():

a = [{'C': 3742, 'A': 38799, 'F': 66, 'D': 848, 'B': 12953, 'E': 140}, {'C': 2319, 'A': 23551, 'F': 33, 'D': 568, 'B': 8192, 'E': 87}]
b = [[i[k] for k in sorted(i)] for i in a]

Upvotes: 1

Bolshoi Booze
Bolshoi Booze

Reputation: 514

Use List comprehension. Avoid using loops.

 y = [[i[key]for key in sorted(i.keys())] for i in x]

Upvotes: 1

PaxPrz
PaxPrz

Reputation: 1928

Add a list instead of adding individual elements in res list.

res = []
for i in range(len(a)):
    temp = []
    for e in sorted(a[i].keys()):
        temp.append(a[i][e])
    res.append(temp)

Upvotes: 0

tituszban
tituszban

Reputation: 5152

You want to put the result of from the dictionaries to an array, before adding to the final results

a = [{'C': 3742, 'A': 38799, 'F': 66, 'D': 848, 'B': 12953, 'E': 140}, {'C': 2319, 'A': 23551, 'F': 33, 'D': 568, 'B': 8192, 'E': 87}]
res = []
for i in range(len(a)):
    sub_res = []
    for e in sorted(a[i].keys()):
        sub_res.append(a[i][e])
    res.append(sub_res)

A shorter version of this would be:

res = [ [i[e] for e in sorted(i.keys())] for i in a ]

Upvotes: 3

Related Questions