[英]How to select a value of a key in dictionary based on the value of another key
在以下詞典中:
dic = {'x':[1, 2, 3], 'y':[11, 12 , 13]}
當與鍵'y'
對應的列表元素為12
時,我想從與鍵'x'
對應的列表中檢索值2
。
一個靈活的解決方案是根據dic
的值創建一個查找字典:
>>> dic = {'x':[1, 2, 3], 'y':[11, 12 , 13]}
>>> lookup = dict(zip(dic['y'], dic['x']))
>>> lookup
{11: 1, 12: 2, 13: 3}
>>> lookup[12]
2
如果你想要一個x
基於給定的位置y
,我建議使用zip()
def find_x(dic, target_y):
pairs = zip(dic['x'], dic['y'])
for x, y in pairs:
if y == target_y:
return x
事實上,如果你經常做這種事情。 最好將 x 和 y 值存儲為對(或字典或類對象)的列表,而不是具有單獨的 x 和 y 列表的字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.