Home > Enterprise >  compare two list and set zero for not exist value
compare two list and set zero for not exist value

Time:11-28

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

CodePudding user response:

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}

CodePudding user response:

This should work:

result = {key : 1 if key in lst2 else 0 for key in lst}
  • Related