3

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.

Anonymous Entity
  • 3,254
  • 3
  • 27
  • 41

2 Answers2

2

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.
Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
0

I wrote it with itertools and got something utterly less readable:

from itertools import groupby
from operator import itemgetter

d1 = {'a':True, 'b':False, 'c':True}
d2 = {'a':False, 'b':True, 'c':True}

key = itemgetter(0)
value = itemgetter(1)

d3 = {key: all(map(value, values))
      for key, values in groupby(sorted(d1.items() + d2.items()), key)}

I find your version a whole lot more readable.

(I know that's not exactly what you asked for, but that's what I came up with while trying to give a real answer and needed to share it with someone.)

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65