2014-03-26 68 views
-1

是否有一个函数可以接受字典并修改字典只需增加1中的值?增加字典中的值?

f({'1':0.3, '11':2, '111':{'a':7, 't':2}}) 

变得

{'1':1.3, '11':3, '111':{'a':8, 't':3}} 

f({'a':{'b':{'c':5}}})

变得

{'a':{'b':{'c':6}}} 

谢谢!

+1

没有内置函数'dictionary_value_one_adder'!你有没有试图实现它? – jonrsharpe

+2

它是你的功课吗? http://stackoverflow.com/questions/22655674/modify-value-in-dictionary – zhangxaochen

回答

1

不是最好的...

def incr(d): 
    try: 
     return d + 1 
    except TypeError: # test the type rather catch error 
     return g_incr(d) 
    except: 
     return 0 
def g_incr(d): 
    return {k:incr(v) for k, v in d.items()} 


test = {'1':0.3, '11':2, '111':{'a':7, 't':2}} 
print g_incr(test) 
0

我想你应该试试这个;

def increment(dict): 
    return {k:v+1 for k,v in dict.items()} 
result = increment() 
print result