Home > Back-end >  Replace Value on dict comprehension based on condition
Replace Value on dict comprehension based on condition

Time:11-23

a = ('A','B','C')
b = (45.43453453, 'Bad Val', 76.45645657 )

I want to create a dict, very simple:

{ k:v for k,v in zip(a,b) }

My problem is, now I want to apply float (if possible) or replace it with None

so, I want to apply a round of 2 and therefore my output should be:

{'A': 45.43, 'B': None, 'C': 76.46}

CodePudding user response:

Since round raises a TypeError whenever something doesn't implement __round__, this isn't possible directly with dictionary comprehensions, but you can write your own function to use inside of it.

def safe_round(val, decimals):
  try:
    return round(val, decimals)
  except TypeError:
    return None

a = ('A','B','C')
b = (45.43453453, 'Bad Val', 76.45645657 )

d = { k:safe_round(v, 2) for k,v in zip(a,b) }
{'A': 45.43, 'B': None, 'C': 76.46}

CodePudding user response:

define a function like

def try_round(n, d):
    try:
        return round(n, d)
    except TypeError:
        return None

and then

result = {k: try_round(v, 2) for k, v in zip(a, b)}
  • Related