compare two list and set zero for not exist value

Question:

I want to compare lst2 with lst and set zero for value who is not exist

lst = ['IDP','Remote.CMD.Shell','log4j']

lst2 = ['IDP']

I want output like this in for example loop

{
IDP:1,
Remote.CMD.Shell:0,
log4j:0
}
{
IDP:0,
Remote.CMD.Shell:0,
log4j:0
}
{
IDP:0,
Remote.CMD.Shell:0,
log4j:0
}

I would be glad if anyone can help me

Asked By: alfred

||

Answers:

Here is how i can achieve this

first you can create a new dictionary and then manipulate the data inside

lst = ['IDP','Remote.CMD.Shell','log4j']

lst2 = ['IDP']

result = {}

for i in lst:
    result[i] = 0

# if one of result keys is in lst2, set the value to 1
for i in lst2:
    if i in result:
        result[i] = 1
    
print(result)

result:
{'IDP': 1, 'Remote.CMD.Shell': 0, 'log4j': 0}

Answered By: Bachrul uluum

This should work:

result = {key : 1 if key in lst2 else 0 for key in lst}
Answered By: Vin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.