繁体   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