簡體   English   中英

比較python中的列表和字典

[英]Compare lists and dictionary in python

我的查詢是獲取列表中的每個項目與字典的鍵進行比較並獲取其值。

代碼:

for each_element in list1:
   for key,value in my_dictionary.items():
       if each_element == key:
          output = value

我面臨的錯誤是列表中的元素是:

list element: ['a','b']
key from dictionary: 'a,b'

這是不匹配的。 有沒有辦法做到這一點?

給 try-except 一個機會並繞過任何不匹配而不產生錯誤。 使用字典的搜索功能 - myDictionary[KeyToSearchFor] 輸出值(如果有)。

L = ['a','b','c','d','e','f']
D = {'a':10,'b':20,'c':30,'d':40,'z':50,'f':60, 'g':70}

for i in L:
    try:
        print("key: {} / value: {}".format(i,D[i]))
    except KeyError:
        continue

輸出,注意“e”上沒有匹配項

key: a / value: 10
key: b / value: 20
key: c / value: 30
key: d / value: 40
key: f / value: 60

假設你的列表是[["a","b"],..]和字典是{"a,b":val1,...}

out = (my_dict.get(",".join(item)) for item in my_list)
# out := [val1, val2, None, None, val3..], None for non-existent keys
# to weed out None vals
out2 = (item for item in out if item)
# and finally, consume the iterator
output = list(out2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM