![](/img/trans.png)
[英]How to retrieve value from Python dictionary based upon match of list of values
[英]Retrieve a python dictionary key based on a value from a list of values
我有一份生活在不同時區的人的名單。 我需要確定這個人屬於哪個時區。
我創建了一個字典:
mydict = {'London':['bob1', 'bob2', 'bob3'],'Paris': ['bob4','bob5','bob6','bob7']}
我發現,我可以根據它的價值得到一個鑰匙
mydict.keys()[mydict.values().index('bob')]
問題是該值存儲在列表中。 有沒有辦法得到它? 也許您可以看到完全不同的問題解決方案? 我想創建一個表 Timezone |customer1|customer2|customern-1 但它似乎也不是一個優雅的解決方案。
mydict = {'London':['bob1', 'bob2', 'bob3'],'Paris': ['bob4','bob5','bob6','bob7']}
person = 'bob5'
for key,item in mydict.items():
if person in item:
print ("Person {} is living in {}".format(person,key))
輸出:
Person bob5 is living in Paris
或者使用list comprehension
:
person = 'bob5'
city = [key for key,item in mydict.items() if person in item]
print ("Person {} is living in {}".format(person,city[0]))
輸出:
Person bob5 is living in Paris
您可以創建一個函數並使其可重用。 如果找到並跳過下一次迭代,您可以檢查人員in
回報
mydict = {'London':['bob1', 'bob2', 'bob3'],'Paris': ['bob4','bob5','bob6','bob7']}
def getKey(mydict,person):
for key in mydict.keys():
if person in mydict[key]:
return key
print(getKey(mydict,'bob1'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.