简体   繁体   English

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

[英]Comparing a dictionary value with a list and returning keys in list's order in Python

I have a dictionary like this:我有一本这样的字典:

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

and a list like this:和一个这样的列表:

top_indices = [311, 992, 451]

I want to compare the dictionary with the list and return the keys of the dictionary.我想将字典与列表进行比较并返回字典的键。 I'm able to do that using this code:我可以使用以下代码做到这一点:

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

This is giving me the result这给了我结果

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

But I want the original order of the list to be unchanged, like this:但我希望列表的原始顺序不变,如下所示:

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

How can I do that?我怎样才能做到这一点?

You should invert the dictionary:你应该反转字典:

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

Now you can look up the keys in the correct order:现在您可以按正确的顺序查找键:

[inverse[index] for index in top_indices]

Another way would be另一种方式是

list(map(inverse.__getitem__, top_indices))

If you swap the keys and the values it would be very easy.如果您交换键和值,那将非常容易。 Try this:尝试这个:

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))

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

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