Matt
Matt

Reputation: 37

How to find a value in a list of dictionaries and return a specific key

I have a list of gpg keys. each in their own dictionary. I want to search though this list of dictionary s by one value '[email protected]' and return the value of the key d['keyid'] in the same dictionary. Here's what i have.:

>>> import gnupg
>>> gpg = gnupg.GPG()
>>> email = '[email protected]'
>>> 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 <[email protected]>']}, {'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 <[email protected]>']}, {'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 <[email protected]>']}]

Now here is the functions that i have tried:

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']

All of the functions either return None or an error. How can i get this to work. and why have i failed so far. Where am i going wrong?

Upvotes: 1

Views: 88

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34146

Try this, may work:

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

Output:

CF7BBCC34CCC28A0
865F4A95D4999F17
1F6A4AEA477EFBD6

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239443

You can use list comprehension and any function, like this

key = '[email protected]'
print [d["keyid"] for d in klist if any(key in uid for uid in d["uids"])]

Output

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

Upvotes: 3

Related Questions