【问题标题】:How can I extract exact key and its values from a dictionary?如何从字典中提取确切的键及其值?
【发布时间】:2020-09-02 02:24:07
【问题描述】:

我有一个单词列表,应该与字典中的某些键匹配。如何返回匹配的键及其值?

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?

【问题讨论】:

  • if term in concepts: ...

标签: python dictionary for-loop key-value


【解决方案1】:

如果键列表与字典的实际键完全匹配,则可以将其用作键。即,在您的示例中,

dictionary[terms[0]] 应该产生['str1', 'str2' ...]。要从列表中获取匹配键的字典的值,您只需这样做

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

【讨论】:

    【解决方案2】:

    为按键快速查找而构建的字典。遍历键是低效的。

    试试这个。它通过键获取值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2020-02-16
      • 2020-11-05
      • 2019-10-04
      • 2013-06-09
      相关资源
      最近更新 更多