[英]Python dict - some keys with the same value
我正在嘗試編寫一個包含國家/地區 GMT 時間(整數)的字典,例如我有一個字典,我想獲取它的值,我嘗試了以下代碼:
countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
print(countires.get('Athens'))
輸出是:
None
我怎樣才能得到結果 2?
IIUC,您需要創建具有單獨密鑰的臨時dict
並搜索您想要的內容,如下所示:
>>> countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
>>> dct = {k:value for key,value in countires.items() for k in key}
>>> print(dct.get('Athens'))
2
如果你想使用你的原始dictionary
你可以定義function
並在如下鍵中搜索:
>>> def search_multi_key(search, dct):
... for key, value in dct.items():
... if search in key:
... return value
... return None
>>> search_multi_key('Athens', countires)
2
一種方法是創建一個新字典,將元組的每個元素用作鍵:
countries= {('Jerusalem', 'Athens', 'Bucharest'):2 , ('Bahrain', 'Qatar'):3}
cities = { key : value for keys, value in countries.items() for key in keys }
print(cities.get('Athens'))
輸出
2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.