【问题标题】:python Dictionary substring keypython字典子字符串键
【发布时间】:2020-07-01 10:32:40
【问题描述】:

我有一个这样的字典

D={'Physician procedure note':a,'Dentistry Procedure note':b,'Podiatry Procedure note':c}

我想在上面的字典中用关键字“程序报告”搜索这本字典。我想找出字典中最近的键附近并提取值。

I have used this approach
search_key = 'Procedure report'
  

# Using items() + list comprehension 
# Substring Key match in dictionary 
result = [val for key, val in D.items() if search_key in key] 
  
# printing result  
print("Values for substring keys : " + str(result)) 

我的列表是空的。我该如何改变这个。

【问题讨论】:

  • 预期输出是什么?
  • 如果我将“程序报告”作为匹配键。我想检索上面字典“医师程序笔记”、“牙科程序笔记”、“足病程序笔记”中的所有键
  • res 字典是什么?您的 D 字典不包含您的 search_key
  • 两者都一样
  • 字典中没有一个键包含文本Procedure report

标签: python-3.x string dictionary


【解决方案1】:

你可以试试

result = [val for key, val in D.items() if any([s.lower() in key.lower() for s in search_key.split(" ")])]
print(result)

输出

['a', 'b', 'c']

【讨论】:

    【解决方案2】:

    你也可以通过检查集合交集来做到这一点:

    search_key = set('Procedure report'.lower().split(" "))
    
    print([v for k, v in D.items() if search_key.intersection(set(k.lower().split(" ")))])
    # ['a', 'b', 'c']
    

    【讨论】:

      【解决方案3】:

      假设您要检索具有与搜索键匹配的对应键的值列表(部分),那么if search_key in key 将不起作用,因为这需要完全匹配。

      你可以做的一种方法是

      # construct a set of search keywords
      keywords = set(search_key.upper().split(" "))
      
      D_filter = list(filter(lambda x: keywords.intersection(set(x[0].upper().split(" "))), D.items()))
      
      result = [term[1] for term in D_filter]
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 2013-07-02
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        相关资源
        最近更新 更多