简体   繁体   English

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

[英]Create new dictionary out of two existing dictionaries

Consider two dictionaries: 考虑两个字典:

dict1 = {'a': 35, 'b': 39, 'c': 20}  # (with the values as integers)

dict2 = {'a': 23, 'c': 12}

I want to obtain the following: 我想获得以下内容:

dict_new = {'a': 0.657, 'c': 0.6}  # (with the values as floats, as values of dict2/dict1)

You can get the common keys using dict2.keys() & dict1 and then just do the division: 您可以使用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}

If you want the values rounded to three decimal places use round(dict2[k] / dict1[k],3) , if the keys from dict2 should always be in dict1 then you can simply iterate over the items of dict2: 如果要将值四舍五入到小数点后三位,请使用round(dict2[k] / dict1[k],3) ,如果dict2中的键始终位于dict1中,则可以简单地遍历dict2的项:

d = {k:v / dict1[k] for k,v in dict2.items()}
dic_new = {}
for key in dic2.keys():
    dic_new[key]=float(dict2[key])/dict1[key]    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM