0

I have a dict with some value in it. Now at the time of fetching value I want to check if value is None replace it with "". Is there any single statement way for this.

a = {'x' : 1, 'y': None}
x = a.get('x', 3) # if x is not present init x with 3
z = a.get('z', 1) # Default value of z to 1
y = a.get('y', 1) # It will initialize y with None
# current solution I'm checking
if y is None:
    y = ""

What I want is something single line (pythonic way). I can do this in below way

# This is one way I can write but 
y = "" if a.get('y',"") is None else a.get('y', "")

But from what I know there must be some better way of doing this. Any help

Pranjal Doshi
  • 862
  • 11
  • 29

3 Answers3

2

If the only falsy values you care about are None and '', you could do:

y = a.get('y', 1) or ''
Jasmijn
  • 9,370
  • 2
  • 29
  • 43
  • 3
    This works if the value is guaranteed to be never 0. – blhsing Aug 11 '21 at 07:12
  • Can you give me some insight on how it works as well. I mean `None or ''`. Why will `''` get assigned. – Pranjal Doshi Aug 11 '21 at 07:17
  • 1
    @PranjalDoshi `None` evaluates to `False` in a boolean test, so `or` will evaluate and return the second operand. See [here](https://realpython.com/python-or-operator/#default-values-for-variables) for a more in-depth explanation. – CrazyChucky Aug 11 '21 at 07:26
2

Jasmijn's answer is very clean. If you need to accommodate other falsy values and you insist on doing it in one line, you could use an assignment expression:

y = "" if (initial := a.get('y', "")) is None else initial

But personally I would prefer your separate if check for clarity over this.

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
0
y = a.get('y',"") or ""
codeape
  • 97,830
  • 24
  • 159
  • 188