Python 使用两个现有词典创建新词典
考虑两个字典:Python 使用两个现有词典创建新词典,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,考虑两个字典: dict1 = {'a': 35, 'b': 39, 'c': 20} # (with the values as integers) dict2 = {'a': 23, 'c': 12} 我想获得以下信息: dict_new = {'a': 0.657, 'c': 0.6} # (with the values as floats, as values of dict2/dict1) 您可以使用dict2.keys()&dict1获取公共密钥,然后只需进行除法: di
dict1 = {'a': 35, 'b': 39, 'c': 20} # (with the values as integers)
dict2 = {'a': 23, 'c': 12}
我想获得以下信息:
dict_new = {'a': 0.657, 'c': 0.6} # (with the values as floats, as values of dict2/dict1)
您可以使用
dict2.keys()&dict1
获取公共密钥,然后只需进行除法:
dict1 = {'a':35, 'b': 39, 'c':20} #(with the values as integers)
dict2 = {'a':23, 'c':12}
d3 = {k: dict2[k] / dict1[k] for k in dict2.keys() & dict1}
如果要将值四舍五入到小数点后三位,请使用四舍五入(dict2[k]/dict1[k],3)
,如果dict2中的键应始终位于dict1中,则可以简单地迭代dict2中的项:
d = {k:v / dict1[k] for k,v in dict2.items()}
那么你试过什么,它到底有什么问题?关于
'b'
,以及dict2
中不在dict1
中的键呢?
dic_new = {}
for key in dic2.keys():
dic_new[key]=float(dict2[key])/dict1[key]