Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用两个现有词典创建新词典_Python_Python 3.x_Dictionary - Fatal编程技术网

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]