簡體   English   中英

將字典值與列表進行比較並在 Python 中按列表的順序返回鍵

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

我有一本這樣的字典:

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']

我怎樣才能做到這一點?

你應該反轉字典:

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

現在您可以按正確的順序查找鍵:

[inverse[index] for index in top_indices]

另一種方式是

list(map(inverse.__getitem__, top_indices))

如果您交換鍵和值,那將非常容易。 嘗試這個:

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