Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a function to values in dict

I want to apply a function to all values in dict and store that in a separate dict. I am just trying to see how I can play with python and want to see how I can rewrite something like this

for i in d:     d2[i] = f(d[i]) 

to something like

d2[i] = f(d[i]) for i in d 

The first way of writing it is of course fine, but I am trying to figure how python syntax can be changed

like image 502
chrise Avatar asked Oct 25 '12 07:10

chrise


People also ask

Can a function be a dictionary value?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.

What is dict () function?

The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.

Is dict () and {} the same?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

What does dict values () return in Python?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.


1 Answers

If you're using Python 2.7 or 3.x:

d2 = {k: f(v) for k, v in d1.items()} 

Which is equivalent to:

d2 = {} for k, v in d1.items():     d2[k] = f(v) 

Otherwise:

d2 = dict((k, f(v)) for k, v in d1.items()) 
like image 185
Joel Cornett Avatar answered Sep 30 '22 11:09

Joel Cornett