【问题标题】:How to find out if element is in any dictionary for specific key in list of dictionaries?如何确定元素是否在字典列表中特定键的任何字典中?
【发布时间】:2023-03-27 07:51:01
【问题描述】:
listofdict = [{'name':"John",'surname':"Adelo",'age':15,'adress':"1st Street 45"},{'name':"Adelo",'surname':"John",'age':25,'adress':"2nd Street 677"},...]

我想检查字典中是否有名字为 John 的人,如果有:真,如果没有:假。这是我的代码:

def search(name, listofdict):
    a = None
    for d in listofdict:
        if d["name"]==name:
            a = True
        else:
            a = False
    print a

但是这不起作用。如果 name=John 它返回 False,但对于 name=Adelo 它返回 True。谢谢。

【问题讨论】:

    标签: python list search dictionary


    【解决方案1】:

    Python 提供的逻辑有助于避免循环的所有复杂性。例如:

    def search(name, listofdict):
        return any( d["name"]==name for d in listofdict )
    

    【讨论】:

    • 抱歉,我看到这是生成器解决方案。
    • 我的意思是,我喜欢你的回答,但它并没有告诉他他的代码有什么问题。
    • 感谢您的回答!
    【解决方案2】:

    您需要在a = True 之后紧跟break

    否则,当目标键不在listofdictlast 字典中时,a 始终为 False。

    顺便说一句,这更干净:

    def search(name, listofdict):
        for d in listofdict:
            if d["name"]==name:
                return True
        return False
    

    【讨论】:

      猜你喜欢
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多