Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function on all values of dictionary [duplicate]

I have dictionary that look like

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

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

I don't wanna re-create the dictionary.

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

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

like image 954
user3378649 Avatar asked Dec 17 '14 03:12

user3378649


People also ask

How do you apply a function to every value in a dictionary?

Use a dictionary comprehension to map a function over all values in a dictionary. Use the syntax {key: f(value) for key, value in dict. items()} to apply the function f to each value in the dictionary dict .

How do you apply a function to a dictionary?

You can use the toolz. valmap() function to apply a function to the dictionary's values. Similarly, to apply function to keys of a dictionary, use toolz. keymap() function and to apply function to items of a dictionary, use toolz.

Can dictionary support duplicate values?

Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list.

Can you put functions in a dictionary Python?

In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.


1 Answers

This is a little more convoluted, but you did ask for a 'pythonic-way' ;)

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

However, this dictionary comprehension will only work on 2.7+. If using an older version of Python, try this more convoluted way:

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

Let me unpack this a little bit:

  • We are beginning by reassigning the new dictionary (d) object back to a new dictionary as requested (although you could easily assign it to the same name)
  • The outer dict() ensures the final result is a dictionary object
  • zip() returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences
  • The first argument sequence given to zip() is the dictionary keys (d.keys())
  • The second argument sequence given to zip() is the rounded values after a list comprehension
  • The list comprehension rounds each value in the dictionary values and returns a list of the rounded values
like image 175
Dan Avatar answered Sep 25 '22 04:09

Dan