0

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.

3
  • I can do that! new_map = { s: True if (s in data) else False for s in all_s} Commented Sep 9, 2016 at 2:05
  • See the answers below. True if (s in data) else False is the same as s in data only more verbose. Commented Sep 9, 2016 at 2:10
  • Yes I notices your answers are better way. But I wanted to note my solution as my study. Thank you for your comment. Commented Sep 9, 2016 at 2:12

3 Answers 3

4

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}
Sign up to request clarification or add additional context in comments.

6 Comments

Arg...beat me by a few seconds. Nice idea to use set() too; I didn't think of that! Although, will the function call make it more expensive?
There is no benefit to using a set if you build the set inside the comprehension :).
Sorry I got lazy typing on my smart phone and didn't want another line. I'll update.
Are there any meanings to use set func?
@jef, k in data_set is faster than k in data if data is large. It's worth using a set if you need to check a large number of keys and data is reasonably large.
|
2

Try a dict comprehension:

new_map = {i: i in data for i in all_s}

4 Comments

Thank you. This is very smart
@elethan Could you spell me out why boolean types (True or False) are return instead of values?
@Monica here I am setting the value in each key-value pair to i in data. i in data == True if i is a value contained in data and False otherwise, so all the values end up as either True or False. Does that make sense?
@elethan yes, it does! Thank you for your explanation! :)
1

I'd use a dictionary comprehension:

x = {i:True if i in data else False for i in all_s}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.