How do I turn every value in my dictionary to a float? (recursively)
d = { 'scores': 4, 'teams': { 'yellow': 11, 'blue': 4 } 开发者_如何学编程 }
How do I take a dictionary, and turn every integer into a float? Recursively, for every value max deep.
def float_dict(d):
new_dict = {}
for k,v in d.iteritems():
if type(v) == dict:
new_dict[k] = float_dict(v)
else:
new_dict[k] = float(v)
return new_dict
>>> d = { 'scores': 4, 'teams': { 'yellow': 11, 'blue': 4 } }
>>> print float_dict(d)
{'scores': 4.0, 'teams': {'blue': 4.0, 'yellow': 11.0}}
def to_float(my_dict):
for i in my_dict:
if type(my_dict[i]) == dict:
my_dict[i] = to_float(my_dict[i])
elif type(my_dict[i]) == int:
my_dict[i] = float(my_dict[i])
return my_dict
defun rec-func (dictionary &optional (current 0))
if dictionary[current] == dict:
rec-func (dictionary[current], 0)
else:
dictionary[current] = float(dictionary[current])
rec-func (dictionary current+1)
It's a recursive function but an iterative process and it's pseudo-code. Also, don't forget to put into some conditional to check if you've reached the end. Probably not the best solution, I haven't even tested it.
Hm, the problem really is getting a specific element of a dictionary but I think my function should work... I hope.
EDIT: Ooops, not properly indented, no idea how to do that though.
edit (santa4nt): Fixed it.
>>> d = { 'scores': 4, 'teams': { 'yellow': 11, 'blue': 4 } }
>>> import pickle
>>> pickle.loads(pickle.dumps(d).replace("\nI","\nF"))
{'scores': 4.0, 'teams': {'blue': 4.0, 'yellow': 11.0}}
note pickle
is recursive :)
精彩评论