在字典中将字典值与列表进行比较,并在Python中按列表的顺序返回键

时间:2020-11-06 07:53:44

标签: python dictionary

我有这样的字典:

dictionary = {'meeting': 311, 'dinner': 451, 'tonight': 572, 'telling': 992, 'one.': 1000}

和类似的列表:

top_indices = [311, 992, 451]

我想将字典与列表进行比较,然后返回字典的键。我可以使用以下代码来做到这一点:

[keys for keys, indices in dictionary.items() if indices in top_indices]

这给了我结果

['meeting',  'dinner', 'telling']

但是我希望列表的原始顺序保持不变,就像这样:

['meeting', 'telling',  'dinner']

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您应该反转字典:

inverse = {index: key for key, index in dictionary.items()}

现在您可以按正确的顺序查找键了:

[inverse[index] for index in top_indices]

另一种方式是

list(map(inverse.__getitem__, top_indices))

答案 1 :(得分:0)

如果交换键和值,将非常容易。 试试这个:

dictionary = {311:'meeting', 451: 'dinner', 572:'tonight', 992:'telling', 1000:'one.'}
top_indices = [311, 992, 451]
x = []
for i in top_indices:
    x.append(dictionary.get(i))
相关问题