簡體   English   中英

如何從字典中提取確切的鍵及其值?

[英]How can I extract exact key and its values from a dictionary?

我有一個單詞列表,應該與字典中的某些鍵匹配。 如何返回匹配的鍵及其值?

terms = ['history', 'patient', 'anotherTerm', ...]


dictionary = {'history': ['str1', 'str2', 'str3'], 
               'clinical': ['str1', 'str2', 'str3'],
               'patient': ['str1', 'str2', 'str3'], ....}

我做了這個打印匹配鍵的循環,但我不確定如何打印鍵的值。 如何確保返回鍵及其值列表?

for c in terms:
        for k in concepts.keys():
            if c == k:
                print("key:", k)  #value?

如果鍵列表與字典的實際鍵完全匹配,則可以將其用作鍵。 即,在你的例子中,

dictionary[terms[0]]應該產生['str1', 'str2'...] 要從列表中獲取匹配鍵的字典的值,您只需執行

for c in terms:
    print("key: ", c)
    print("value: ", dictionary[c])

字典是為按鍵快速查找而構建的。 循環通過密鑰是低效的。

試試這個。 它通過鍵獲取值。

for c in terms:
     print("key:", k)  
     print("value:", concepts[k]

暫無
暫無

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

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