简体   繁体   中英

Sorting data pulled from python dictionary by key

I'm trying to build a matrix that will contains the values from a dictionary, I know dictionaries are unordered but I'd like to sort the values in the matrix (which can be sorted) in a certain order based off the key names in the dictionary.

Let's say I have a dictionary like so:

{'a': 1, 'b': 2, 'c': 3 } 

And a list with the key names in the order that I'd like the data from the matrix to be arranged:

['b', 'c'. 'a']

How can I use the list above to sort the values from the dictonary in a way that gives me a list like so:

[2, 3, 1]

Without explicitly mentioning each key during list comprehension, like so:

data = [ data['b'], data['c'], data['a'] for data in dict ] 

The dictionary that I'm pulling data from has many keys and I'd rather not use the above method to pull 10-15 data points from this dictionary.

I'm not sure what you are doing with that comprehension, but consider:

In [1]: dict = {'a': 1, 'b': 2, 'c': 3 } 

In [2]: keys = ['b', 'c', 'a']

In [3]: [dict[key] for key in keys]
Out[3]: [2, 3, 1]

I'm a big fan of python's functional abilities. Here would be one cool way to use them:

d = {'a': 1, 'b': 2, 'c': 3 }
print map(lambda x: d[x], ['b', 'c', 'a'])

This should give you your solution. What it does is takes each element of the array that you wanted and maps it to the corresponding value in the dictionary. (Basically it does what you mentioned in a functional manner)

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM