Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - Replace all boolean values in a dict by a corresponding value without looping through dict

I have the following dict:

d = {
    "one": False,
    "two": True,
    "three": False,
    "four": True,
    "five": False
    }

I want to replace each instance of True by "Hello" and each instance of False by Good night.

In the end, I want the following dict:

d = {
    "one": "Good night",
    "two": "Hello",
    "three": "Good night",
    "four": "Hello",
    "five": "Good night"
    }

Is there a way to do it without a for loop, or without iterating each value?

Edit: I can still use a for, I just want to know if there's a shorter way to do it than a for block. Also I wanted to know if there was a shorthand to "map" booleans to values in a dicitonary.

I can't manage to do it without browsing/looping through each key/value of the dict. Based on other answers, I tried this: d = d.update( (k,"Hello") for k in d ) but this is for replacing all values, and not on a condition.

question from:https://stackoverflow.com/questions/66049789/replace-all-boolean-values-in-a-dict-by-a-corresponding-value-without-looping-th

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, there's no way to do it without a loop.

for key, val in d.items():
    d[key] = "Hello" if val else "Good night"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...