Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this dictionary comprehension more readable [closed]

I'm wondering how to rewrite this to make it more readable, so I and perhaps others can understand it without any confusion in the future:

d1 = {'a':True, 'b':False, 'c':True}
d2 = {'a':False, 'b':True, 'c':True}
# wanted output: False if either value is False, True only if both are True
# d3 = {'a':False, 'b':False, 'c':True}

d3 = {key: (d1[key] and d2[key]) for key in d1}

I'm not looking for the most possible verbose version, but just what is clear and human readable.

like image 280
Anonymous Entity Avatar asked Dec 02 '25 11:12

Anonymous Entity


1 Answers

What you've got looks very human-readable to me. You could probably rename the three dictionaries to be more descriptive of their purpose, but that's about it. I think about the only way you're going to make it clearer is to expand it into an explicit loop.

# This would be so much nicer with real variable names, don't you agree?
d1_AND_d2 = {}
for key in d1:
    d1_AND_d2[key] = d1[key] and d2.get(key) # Use get in case d1 has more keys.
like image 115
Henry Keiter Avatar answered Dec 05 '25 01:12

Henry Keiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!