如何在python字典上进行数学操作?
我有一本字典如何在python字典上进行数学操作?,python,dictionary,Python,Dictionary,我有一本字典 ex_dict_tot={'recency': 12, 'frequency': 12, 'money': 12} ex_dict_count= {'recency': {'current': 4, 'savings': 2, 'fixed': 6}, 'frequency': {'freq': 10, 'infreq': 2}, 'money': {'med': 2, 'high': 8, 'low': 1,
ex_dict_tot={'recency': 12, 'frequency': 12, 'money': 12}
ex_dict_count= {'recency': {'current': 4, 'savings': 2, 'fixed': 6},
'frequency': {'freq': 10, 'infreq': 2},
'money': {'med': 2, 'high': 8, 'low': 1, 'md': 1}}
另一本算字典
ex_dict_tot={'recency': 12, 'frequency': 12, 'money': 12}
ex_dict_count= {'recency': {'current': 4, 'savings': 2, 'fixed': 6},
'frequency': {'freq': 10, 'infreq': 2},
'money': {'med': 2, 'high': 8, 'low': 1, 'md': 1}}
我想计算每个关键值的比例,如下所示:
在关键时期
current=4/12,
savings=2/12,
fixed=6/12
同样地,在键频方面
freq=10/12
infreq=2/12
所需的输出是
{'recency': {'current': 0.3, 'savings': 0.16, 'fixed': 0.5},
'frequency': {'freq': 0.83, 'infreq': 0.16},
'money': {'med': 0.16, 'high': 0.6, 'low': 0.08, 'md': 0.08}}
你能在上面写下你的建议/意见吗?你可以通过听写理解来做到这一点
用于获取浮点精度为2的值
out = {key:{k:round(v/ex_dict_tot[key],2) for k,v in val.items()} for key,val in ex_dict_count.items()}
out
{'recency': {'current': 0.33, 'savings': 0.17, 'fixed': 0.5},
'frequency': {'freq': 0.83, 'infreq': 0.17},
'money': {'med': 0.17, 'high': 0.67, 'low': 0.08, 'md': 0.08}}
你可以通过听写理解来做到这一点
用于获取浮点精度为2的值
out = {key:{k:round(v/ex_dict_tot[key],2) for k,v in val.items()} for key,val in ex_dict_count.items()}
out
{'recency': {'current': 0.33, 'savings': 0.17, 'fixed': 0.5},
'frequency': {'freq': 0.83, 'infreq': 0.17},
'money': {'med': 0.17, 'high': 0.67, 'low': 0.08, 'md': 0.08}}
字典['recenty']['current']=字典['recenty']['current']/=12字典['recenty']['current']/=12字典['recenty']['current']/=12或更短的字典['recenty']['current']/=12