-2

I want to iterate over a dict and do some calculations with the data. But I don't want NoneType data, else I get an error. So I do this:

sum_value = 0 if values.get("sum", 0) is None else values.get("sum", 0)

Isn't there a better way to do this in Python?

sg_sg94
  • 2,248
  • 4
  • 28
  • 56

4 Answers4

6

You could do:

sum_value = values.get("sum") or 0

The or will pick the second operand for all false (falsy) first operands which includes None, but excludes all non-zero numbers.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • what does the or? – sg_sg94 Jan 13 '21 at 12:49
  • In general, both `and` and `or` evaluate to the first operand that determines the outcome wrt to truthiness. For `and` that is the first falsy operand (or the last one overall if there is no truthy one), for `or` it is the first truthy operand (or the last one overall). – user2390182 Jan 13 '21 at 12:51
0

I believe that values.get("sum", 0) is already sufficient, as the 0 is the default value returned if the dictionary does not contain anything under the specified key.

DanDayne
  • 154
  • 6
0

I would just use an ordinary if statement to update the value, captured using an assignment statement in Python 3.8 or later

if (sum_value := values.get("sum", 0)) is None:
    sum_value = 0

or prior to the if statement in earlier versions of Python.

sum_value = values.get("sum", 0)
if sum_value is None:
    sum_value = 0

You can use the assignment expression in a conditional expression as well:

sum_value = 0 if (x:=values.get("sum", 0)) is None else x
chepner
  • 497,756
  • 71
  • 530
  • 681
-1

I think you're looking for a dictionary comprehension:

{x:(y if y else 0) for x,y in r.items()}

here's another good post on it

How can I use if/else in a dictionary comprehension?

m25
  • 1,473
  • 2
  • 13
  • 14
  • 1
    `NoneType` is not an existing built-in name. Test `if y is None` instead, or do `x: y or 0`. – user2390182 Jan 13 '21 at 13:01
  • Even if it *were* a built-in name, comparing types for equality is frowned upon. – chepner Jan 13 '21 at 13:27
  • @chepner That's of course the next issue =) In particular for a type that only has a single instance, hence the hint to test for instance identity. – user2390182 Jan 13 '21 at 13:53
  • Thanks for the feedback. I guess I should have ran the code before posting :). Response edited. Why is it typically frowned upon to do a type comparison? Is that a general rule or specifically in this instance? @chepner – m25 Jan 13 '21 at 15:57
  • 1
    At the very least, it bypasses inheritance. For example, `type(True) == int` is false, but `True` is an `int`, in the sense that `bool` is a subclass of `int`. You rarely care about the *exact* type of a value. – chepner Jan 13 '21 at 16:00