Apply function for all dictionary values

I have a dictionary similar to

d= {(1, 8): 94.825000000000003, (2, 8): 4.333} 

I am trying to apply a function to round all values.

I do not want to recreate the dictionary.

 newD= {} for x,y in d.iteritems(): newD+= {x:round(y)} 

Is there any pythonic way to apply the round function to all values?

+5
source share
2 answers

This is a bit more confusing, but you asked for a "pythonic-way";)

 newD = {k:round(v) for k, v in d.items()} 

However, this dictionary understanding will only work on 2.7+. If you are using an older version of Python, try to do it in a more confusing way:

 newD = dict(zip(d.keys(), [round(v) for v in d.values()])) 

Let me unpack a little:

  • We start by reassigning the new dictionary ( d ) back to the new dictionary upon request (although you can easily assign it with the same name)
  • External dict() provides the final result - a dictionary object
  • zip() returns a list of tuples, where the i-th tuple contains the i-th element from each sequence of arguments
  • The first sequence of arguments provided by zip() is the dictionary keys ( d.keys() )
  • The second sequence of arguments given by zip() are rounded values ​​after understanding the list.
  • Understanding the list rounds each value in dictionary values ​​and returns a list of rounded values
+5
source

You can try something like this:

 for k, v in d.iteritems(): d[k] = round(v) 

It will do the rounding of all elements in the dictionary in place. In this particular example, this will work fine, but be careful - all the normal caveats about using a round function apply.

+5
source

Source: https://habr.com/ru/post/1209296/


All Articles