我有以下列表,
admin_extra = [
{
'name': 'nikhil',
'passkey': 'nikhilpasskey'
},
{
'name': 'mac',
'passkey': 'macpasskey'
},
]
如何以更好的方式获取列表中的dicts? 如果找不到匹配项,则打印错误?
我已经完成了
name = 'nikhil'
flag = 0
for admin in admin_extra:
if admin['name'] == name:
passkey = admin[passkey]
flag = 1
return passkey
if not flag:
print "not found"
我也希望消除标志逻辑
答案 0 :(得分:1)
最明显的方法是使用break
语句。
passkey = None
for admin in admin_extra:
if admin['name'] == name:
passkey = admin["passkey"]
break
if passkey is None:
print "not found"
或者使用列表理解:
matching_admin_extras = [ae for ae in admin_extra if ae["name"] == name]
if len(matching_admin_extras)==0:
print "not found"
elif len(matching_admin_extras)>1:
print "multiple matches"
else:
print matching_admin_extras[0]["passkey"]
答案 1 :(得分:1)
name = 'nikhil'
try:
passkey = [admin['passkey'] for admin in admin_extra if admin['name'] == name][0]
except IndexError:
print "No passkey found for", name
答案 2 :(得分:1)
一种方法是将代码放在一个函数中(因为它看起来像是return
的存在:
def get_passkey(admin_extra, name):
for admin in admin_extra:
if admin['name'] == name:
passkey = admin[passkey]
return passkey
# this will not happen if we have left the function due to returning the passkey
return None # We did not find a passkey
另一种方法是使用break语句:
name = 'nikhil'
passkey = ''
for admin in admin_extra:
if admin['name'] == name:
passkey = admin[passkey]
print passkey
break
else:
print "not found"
其他(部分诙谐)建议:使用classes。
示例代码:
admins = AdminList(Admin("Nikhil", "nikhilpasskey"), Admin("Mac", "macpasskey"))
pass = admins["Nikhil"].passkey
答案 3 :(得分:0)
filtered=[item['passkey'] for item in admin_extra if item['name'] == name]
return filtered[0] if filtered else 'not found'
答案 4 :(得分:-1)
您可以使用列表理解:
ae_names = [ae['name'] for ae in admin_extra]
if name not in ae_names:
print "not found"