Search code examples
pythondictionaryroundingpython-zip

Replace Value on dict comprehension based on condition


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}

Solution

  • 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}