I have two lists
list1=['ABC','DBA','CBA','RBA','DCA','RMA']
list2=['ABC,'DBA','RMA']
Expected Output
{'ABC':1,'DBA':1,'CBA':0,'RBA':0,'DCA':0,'RMA':1}
if the values of list1 are present in list2 then the values of output dictionary would be 1, otherwise 0.
CodePudding user response:
If the size of list2
is small, you can use a simple dictionary comprehension:
{key: int(key in list2) for key in list1}
However, if list2
is long, you should turn it into a set for faster lookups:
lookup_set = set(list2)
{key: int(key in lookup_set) for key in list1}
Both of these output:
{'ABC': 1, 'DBA': 1, 'CBA': 0, 'RBA': 0, 'DCA': 0, 'RMA': 1}
CodePudding user response:
list1=['ABC','DBA','CBA','RBA','DCA','RMA']
list2=['ABC','DBA','RMA']
output = {}
for x in list1:
output[x] = 0
for x in list2:
if (x in output):
output[x] = 1
else:
output[x] = 0
print(output) # {'ABC': 1, 'DBA': 1, 'CBA': 0, 'RBA': 0, 'DCA': 0, 'RMA': 1}
CodePudding user response:
If list1 will always contain all possible keys
{s:int(s in list2) for s in list1}
But in the general case, where there could be distinct keys in either, this will work
{s:int(s in list2 and s in list1) for s in list1 list2}
Note: Because python can automatically interpret booleans as integers then the only reason to cast to int is if you need to print the dictionary. Otherwise I would just leave the values as True/False