[英]How can I extract exact key and its values from a dictionary?
I have a list of words that should match some of the keys in the a dictionary.我有一个单词列表,应该与字典中的某些键匹配。 How can I return the matching keys an their values?如何返回匹配的键及其值?
terms = ['history', 'patient', 'anotherTerm', ...]
dictionary = {'history': ['str1', 'str2', 'str3'],
'clinical': ['str1', 'str2', 'str3'],
'patient': ['str1', 'str2', 'str3'], ....}
I did this loop that prints the matching keys, but I'm not sure how to print the key's values as well.我做了这个打印匹配键的循环,但我不确定如何打印键的值。 How can I make sure to return the key and its list of values?如何确保返回键及其值列表?
for c in terms:
for k in concepts.keys():
if c == k:
print("key:", k) #value?
If the list of keys match exactly with the actual keys of the dictionary, you can just use it as the key.如果键列表与字典的实际键完全匹配,则可以将其用作键。 Ie, in your example,即,在你的例子中,
dictionary[terms[0]]
should produce ['str1', 'str2'...]
. dictionary[terms[0]]
应该产生['str1', 'str2'...]
。 To get the values of a dictionary matching keys from your list, you would just do要从列表中获取匹配键的字典的值,您只需执行
for c in terms:
print("key: ", c)
print("value: ", dictionary[c])
A dictionary is built for fast lookups by key.字典是为按键快速查找而构建的。 Looping through the keys is inefficient.循环通过密钥是低效的。
Try this instead.试试这个。 It gets the values by key.它通过键获取值。
for c in terms:
print("key:", k)
print("value:", concepts[k]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.