I'd like to run a function on all the values in a dictionary. To make things more complicated, the exact transformation each value goes through is not independent, but contingent on the transformations other values before it went through. Here's a simple function, defined on a list, to show what I mean:
def new_list_generator(mylist):
number_of_iterations = 0
new_list = []
for n in mylist:
if number_of_iterations%2 == 0:
new_list.append(n**1.25)
number_of_iterations += 1
else:
new_list.append(n**0.5)
number_of_iterations += 1
return new_list
You can see that the power we employ on each value depends on the the history - how many values were modified before it.
Now, that's the function defined for a list. What happens when I want to modify a dictionary's values without disassociating keys and values (that is, I don't want to simply create a list of all the values and feed that list to the function)?
The best solution I could think of (and make it work) was the following cumbersome solution:
step 1: transform the dictionary to a list of tuples. i.e. [(value1,key1), (value2,key2),...]
step 2: run a modified function on that list.
step 3: convert the list back to a dictionary with dict().
That is:
some_dict = {"Graham": 13, "Eric": 19, "Terry G": 7, "Terry J":11, "John": 15, "Michael": 7}
dict_to_tuples = some_dict.items()
def new_list_generator1(mylist): # notice it's a new function
number_of_iterations = 0
new_list = []
for n in mylist:
if number_of_iterations%2 == 0:
new_list.append((n[0],n[1]**1.25)) # <== new
number_of_iterations += 1
else:
new_list.append((n[0],n[1]**0.5)) # <== new
number_of_iterations += 1
return new_list
tups = new_list_generator1(dict_to_tuples)
print dict(tups)
I was wondering if there's a less cumbersome way to do that, hopefully without having to modify the original list. I googled around and couldn't find anything informative on Stackoverflow or elsewhere (where the function employed on dict values depends on history).
Thanks for your help.