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 ?
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 .
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.
Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list.
In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.
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:
d
) object back to a new dictionary as requested (although you could easily assign it to the same name)dict()
ensures the final result is a dictionary objectzip()
returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequenceszip()
is the dictionary keys (d.keys()
)zip()
is the rounded values after a list comprehensionIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With