如何确定元素是否在字典列表中特定键的任何字典中?
How to find out if element is in any dictionary for specific key in list of dictionaries?
listofdict = [{'name':"John",'surname':"Adelo",'age':15,'adress':"1st Street 45"},{'name':"Adelo",'surname':"John",'age':25,'adress':"2nd Street 677"},...]
我想检查字典中是否有任何名字叫 John 的人,如果有:True,如果没有:False。这是我的代码:
def search(name, listofdict):
a = None
for d in listofdict:
if d["name"]==name:
a = True
else:
a = False
print a
但是这不起作用。如果 name=John 它 returns False,但是对于 name=Adelo 它 return True。谢谢
您需要在 a = True
之后 break
。
否则,当目标键不在 listofdict
.
的 last 字典中时,a
始终为 False
顺便说一下,这个更干净:
def search(name, listofdict):
for d in listofdict:
if d["name"]==name:
return True
return False
Python 提供有助于避免所有复杂循环的逻辑。例如:
def search(name, listofdict):
return any( d["name"]==name for d in listofdict )
listofdict = [{'name':"John",'surname':"Adelo",'age':15,'adress':"1st Street 45"},{'name':"Adelo",'surname':"John",'age':25,'adress':"2nd Street 677"},...]
我想检查字典中是否有任何名字叫 John 的人,如果有:True,如果没有:False。这是我的代码:
def search(name, listofdict):
a = None
for d in listofdict:
if d["name"]==name:
a = True
else:
a = False
print a
但是这不起作用。如果 name=John 它 returns False,但是对于 name=Adelo 它 return True。谢谢
您需要在 a = True
之后 break
。
否则,当目标键不在 listofdict
.
a
始终为 False
顺便说一下,这个更干净:
def search(name, listofdict):
for d in listofdict:
if d["name"]==name:
return True
return False
Python 提供有助于避免所有复杂循环的逻辑。例如:
def search(name, listofdict):
return any( d["name"]==name for d in listofdict )