2

我有以下清单,

admin_extra = [
                {
                   'name': 'nikhil',
                    'passkey': 'nikhilpasskey' 
                },

                {
                    'name': 'mac',
                    'passkey': 'macpasskey' 
                },
             ]

如何以更好的方式在列表中获取字典?如果找不到匹配项,则打印错误?

我已经完成了

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"

我也希望消除标志逻辑

4

5 回答 5

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
于 2013-08-20T12:13:42.357 回答
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
于 2013-08-20T12:13:43.737 回答
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"]
于 2013-08-20T12:11:17.567 回答
0
filtered=[item['passkey'] for item in admin_extra if item['name'] == name]
return filtered[0] if filtered else 'not found'
于 2013-08-20T12:18:18.540 回答
-1

您可以使用列表推导:

ae_names = [ae['name'] for ae in admin_extra]

if name not in ae_names:
    print "not found"
于 2013-08-20T12:09:42.893 回答