-2

Here is the operation that I want to perform:

        for sample in samples:
            if sample['something'] is None:
                sample['something'] = 'something_else'

I want to write this in a more elegant and Pythonic way. It would be great if some experts in Python could help. samples is a list of dictionaries.

Parth
  • 35
  • 8

1 Answers1

2
for sample in (elt for elt in samples if elt["something"] is None):
    sample["something"] = "something_else"

Note use of generator expression to not build another in-memory list, though this might be unnecessary.

I also would not use explicit None check either, unless empty collections, strings or 0 should be considered "truthy" values -- often they aren't, with the exception of zero. if not foo reads IMO better than if foo is not None. If this is your case too, you could do just

for sample in samples:
    sample["something"] = sample["something"] or "something_else"

Then again I wouldn't probably bother, original would be good enough for me, and like suggested in comments, using or shortcut could be a tad hacky (in a bad way) for some readers.

EdvardM
  • 2,934
  • 1
  • 21
  • 20