'How to one-string code write to multi-strings
I am a new to python. I have a dictonary and a list. like this:
dict1 = {'[email protected]': 'John Smith', '[email protected]': 'James Brown'}
list1 = ['[email protected]', '[email protected]', '[email protected]']
I need to compare email from the list with key from dictonary, if it's the same, then print value from dictonary.
I found a great decision:
result = {k:dict1[k] for k in list1 if k in dict1}
It's returns dictonary.
But how to rewrite this in multiline view? I need to add: elif value from list1 != key from dict1 then print value from list1.
Solution 1:[1]
Without a comprehension:
for email in list1:
if email not in dict1:
print(email)
# Output
[email protected]
Or with a comprehension:
print(*[email for email in list1 if email not in dict1], sep='\n')
# Output
[email protected]
Solution 2:[2]
How about this one liner?
dict1 = {'[email protected]': 'John Smith', '[email protected]': 'James Brown'}
list1 = ['[email protected]', '[email protected]', '[email protected]']
print('\n'.join(list(filter(lambda x:x not in dict1,list1))))
output:
[email protected]
Solution 3:[3]
Get a list of emails not found in dict1 using list comprehension:
not_found = [i for i in list1 if i not in dict1]
You can run for loop on this "not_found" var.
Solution 4:[4]
You will have a better control over your data processing if you convert your dict comprehension into a classical for-loop like so:
results = {}
for k in list1:
if k in dict1:
results[k] = dict1[k]
else:
results[k] = "no name"
print(k)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Corralien |
Solution 2 | Nanthakumar J J |
Solution 3 | |
Solution 4 |