简体   繁体   English

按键对从python字典中提取的数据进行排序

[英]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. 我从中提取数据的字典有很多键,我宁愿不使用上述方法从该字典中提取10-15个数据点。

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. 我非常喜欢python的功能。 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! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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