将列表按各自的值在单独的字典中排序?

问题描述 投票:0回答:3

说我有字典,其中一些键是单独数组中的值,如何通过字典中它们各自键的值对数组中的值进行排序?

例如:

输入:

dict = {'a': 4, 'b': 7, 'c': 10, 'd': 1}
array = [a, b, d]

输出:

array = ['d', 'a', 'b']

输出数组中值的顺序首先是“ d”,因为它在字典中的值最低(1)。后跟“ a”(4)和“ b”(7)。我故意不在数组中包含“ c”。

我不要求通过算法解决此问题

我问是否有简单的内置方法来执行此操作,例如使用sorted(array, key= )类型的函数。

python arrays sorting dictionary
3个回答
2
投票

我认为您要的是:

>>> d = {'a': 4, 'b': 7, 'c': 10, 'd': 1} 
>>> a = ['a', 'b', 'd']
>>> sorted(a, key=d.get)
['d', 'a', 'b']

0
投票

是的,您可以使用lambda函数来返回字典中相应元素的值。顺便说一句,我认为对变量名使用“ dict”一词不是一个好习惯,因为它是python中的内置词。

print(sorted(array, key=lambda x: a_dict[x]))

0
投票

您可以尝试以下操作:dict = {'a':4,'b':7,'c':10,'d':1}数组= [“ a”,“ b”,“ d”]

new_dict = sorted(dict.items(), key=lambda x: x[1])

output_array = []
for key, value in new_dict:
    check_values = key in array
    if(check_values == True):
        output_array.append(key)

print(output_array)`
© www.soinside.com 2019 - 2024. All rights reserved.