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

将字典值与列表进行比较,并返回列表中的键';Python中的s顺序,python,dictionary,Python,Dictionary,我有一本这样的字典: dictionary = {'meeting': 311, 'dinner': 451, 'tonight': 572, 'telling': 992, 'one.': 1000} top_indices = [311, 992, 451] ['meeting', 'telling', 'dinner'] 下面是一个列表: dictionary = {'meeting': 311, 'dinner': 451, 'tonight': 572, 'telling':

我有一本这样的字典:

dictionary = {'meeting': 311, 'dinner': 451, 'tonight': 572, 'telling': 992, 'one.': 1000}
top_indices = [311, 992, 451]
['meeting', 'telling',  'dinner']
下面是一个列表:

dictionary = {'meeting': 311, 'dinner': 451, 'tonight': 572, 'telling': 992, 'one.': 1000}
top_indices = [311, 992, 451]
['meeting', 'telling',  'dinner']
我想将字典与列表进行比较,并返回字典的键。我可以使用以下代码执行此操作:

[keys for keys, indices in dictionary.items() if indices in top_indices]
这是给我的结果

['meeting',  'dinner', 'telling']
但我希望列表的原始顺序保持不变,如下所示:

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

我该怎么做呢?

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

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

你应该把字典翻过来:

inverse = {index: key for key, index in dictionary.items()}
现在,您可以按正确的顺序查找钥匙:

[inverse[index] for index in top_indices]
另一种方法是

list(map(inverse.__getitem__, top_indices))

索引对于所有项目都是唯一的,如果是这样的话,您可以尝试使用for循环和append到一个列表来反转dict并通过键查找值。命名像
dictionary
这样的变量是不好的。谢谢!解决了!