如何在字典列表中查找值并返回特定键

时间:2014-01-05 03:56:40

标签: python python-2.7 dictionary

我有一个gpg键列表。每个都在自己的字典里。我想通过一个值'foo@foo.bar'来搜索这个字典列表,并在同一个字典中返回键d ['keyid']的值。这就是我所拥有的。:

>>> import gnupg
>>> gpg = gnupg.GPG()
>>> email = 'foo@foo.bar'
>>> keyIn = gpg.gen_key_input(name_real = 'works' , name_email = 
>>> email,key_type='RSA',key_length=1024)
>>> key = gpg.gen_key(keyIn)
>>> klist = gpg.list_keys()
>>> print klist
[{'dummy': u'', 'keyid': u'CF7BBCC34CCC28A0', 'expires': u'1420347600', 'subkeys': [], 'length': u'1024', 'ownertrust': u'u', 'algo': u'1', 'fingerprint': u'5D917845BF81E47403265380CF7BBCC34CCC28A0', 'date': u'1388889639', 'trust': u'u', 'type': u'pub', 'uids': [u'works <foo@foo.bar>']}, {'dummy': u'', 'keyid': u'865F4A95D4999F17', 'expires': u'1420347600', 'subkeys': [], 'length': u'1024', 'ownertrust': u'u', 'algo': u'1', 'fingerprint': u'C081E6552B027E2DA4143852865F4A95D4999F17', 'date': u'1388890408', 'trust': u'u', 'type': u'pub', 'uids': [u'works <foo@foo.bar>']}, {'dummy': u'', 'keyid': u'1F6A4AEA477EFBD6', 'expires': u'1420347600', 'subkeys': [], 'length': u'1024', 'ownertrust': u'u', 'algo': u'1', 'fingerprint': u'B306139A3D740CECA71D9F281F6A4AEA477EFBD6', 'date': u'1388890595', 'trust': u'u', 'type': u'pub', 'uids': [u'works <foo@foo.bar>']}]

现在这里是我尝试过的功能:

def idfind(klist):
    global email
    for k in klist:
        if email in k.items():
            return k

def idfind(l):
    global email
    for d in l:
        if any(d[email]):
            return d['keyid']

def idfind(l, val):
    for d in l:
        for v in d[k]:
            if val in v:
                return d['keyid']

def idfind(lst,val):
    for d in lst:
        if isinstance(d,dict):
            for k,v in d.items():
                if val in k:
                    return d['keyid']

def idfind(lst,val):
    for d in lst:
        if isinstance(d,dict):
            for k,v in d.items():
                if val == v:
                    return d['keyid']

所有函数都返回None或错误。我怎样才能让它发挥作用。为什么我到目前为止失败了。我哪里错了?

2 个答案:

答案 0 :(得分:3)

您可以使用列表推导和any功能,例如

key = 'foo@foo.bar'
print [d["keyid"] for d in klist if any(key in uid for uid in d["uids"])]

<强>输出

[u'CF7BBCC34CCC28A0', u'865F4A95D4999F17', u'1F6A4AEA477EFBD6']

答案 1 :(得分:2)

试试这个,可能会有效:

def idfind(klist):
    for d1 in a:
        for e in d1['uids']:
            if email in e:
                print d1['keyid']

<强>输出:

CF7BBCC34CCC28A0
865F4A95D4999F17
1F6A4AEA477EFBD6