Reputation: 4083
I want to create map data from 2 list data. I have a simple example like below. What I want to do is create 'new_map' data like below. If it contains specific data, the value should be True.
all_s = ['s1', 's2', 's3', 's4']
data = ['s2', 's4']
new_map = {'s1': False, 's2': True, 's3': False, 's4': True}
Are there any smart way (like lambda) to implement this? My python env is 3.X. Of course I can resolve this problem if I use for-iter simply. But I wonder there are better ways.
Upvotes: 0
Views: 1653
Reputation: 1070
I'd use a dictionary comprehension:
x = {i:True if i in data else False for i in all_s}
Upvotes: 1
Reputation: 2343
This should do it quickly and efficiently in a pythonic manner:
data_set = set(data)
new_map = {k: k in data_set for k in all_s}
Upvotes: 4
Reputation: 16993
Try a dict comprehension:
new_map = {i: i in data for i in all_s}
Upvotes: 2