Peter Clement Peter Clement - 6 months ago 9
Python Question

Manipulating a list of dictionaries based on values in another list

So basically I have three lists like so:

list1 = [{
'IP' : "1.1.1.1",
'ID' : 1,
},
{
'IP' : "2.2.2.2",
'ID' : 2
}]

list2 = [{
'vulnerability_id' : 4567,
'ID' : 1,
},
{
'vulnerability_id' : 6578,
'ID' : 2
}]

list3 = [{
'vulnerability_id' : 4567,
'description' : 'blah',
},
{
'vulnerability_id' : 6578,
'description' : 'blah blah'
}]


What I need to do is get the description of an vulnerability based on an IP but this probably requires some sort of list comprehension and im not sure how to go about that. (And put it in a new dictionary)

I need to check the IP value I have, say 1.1.1.1, then compare it's ID with list2, then compare the associated 'vulnerability_id' in list3.

Any help would be greatly appreciated, if this doesn't make sense, please say and I will try and expand.

Answer
list1 = [
    {
        'IP': '1.1.1.1',
        'ID': 1,
    },
    {
        'IP': '2.2.2.2',
        'ID': 2
    }]

list2 = [
    {
        'vulnerability_id': 4567,
        'ID': 1,
    },
    {
        'vulnerability_id': 6578,
        'ID': 2
    }]

list3 = [
    {
        'vulnerability_id': 4567,
        'description': 'blah',
    },
    {
        'vulnerability_id': 6578,
        'description': 'blah blah'
    }]


def find(data, key, value):
    for row in data:
        if row[key] == value:
            return row
    raise ValueError('Row with %s = %s not found' % (key, value))


ID = find(list1, 'IP', '1.1.1.1')['ID']
vulnerability_id = find(list2, 'ID', ID)['vulnerability_id']
print(find(list3, 'vulnerability_id', vulnerability_id)['description'])