从两个现有词典中创建新词典

时间:2015-11-01 10:45:58

标签: 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)

2 个答案:

答案 0 :(得分:3)

您可以使用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}

如果你希望四舍五入到三位小数的值使用round(dict2[k] / dict1[k],3),如果来自dict2的键应该总是在dict1中,那么你可以简单地迭代dict2的项目:

d = {k:v / dict1[k] for k,v in dict2.items()}

答案 1 :(得分:0)

dic_new = {}
for key in dic2.keys():
    dic_new[key]=float(dict2[key])/dict1[key]