如何根据其键和值比较字典并计算一个比率
我有一个字典
dict1={'A': ['15', '3'],'B': ['14', '3']}
,每个密钥的第一个值是我的总数,所以A的总数为15,而B的总数为14。 我
dict2={'A': {'A.X': '20.41%',
'A.Y': '30.59%',
'B.X': '20.09%',
'B.Y': '10.00%',
'C.X': '8.04%',
'C.Y': '10.87%'},
'B': {'B.X': '35.15%',
'B.Y': '50.85%',
'C.X': '0.00%',
'C.Y': '0.00%',
'D.X': '14.00%',
'D.Y': '0.00%'}}
想将每个dict1键的总数应用于同一键的dict2值,以获取总计的比率,例如
dict3={'A': {'A.X': '3.06',
'A.Y': '4.59',
'B.X': '3.01',
'B.Y': '1.5',
'C.X': '1.2',
'C.Y': '1.63'},
'B': {'B.X': '4.92',
'B.Y': '7.12',
'C.X': '0',
'C.Y': '0',
'D.X': '1.96',
'D.Y': '0'}}
我以为我可能会开始,
new_dict = { key : dict1[key]*dict2[key][0] for key in dict1 if key in dict2 }
但这无效。任何帮助都将受到赞赏 PS我是Python的新手,并提前感谢。
I have a dictionary as
dict1={'A': ['15', '3'],'B': ['14', '3']}
and my first value of each key is my total so A's total is 15 and B's total is 14.
I have another dictionary dict2 as
dict2={'A': {'A.X': '20.41%',
'A.Y': '30.59%',
'B.X': '20.09%',
'B.Y': '10.00%',
'C.X': '8.04%',
'C.Y': '10.87%'},
'B': {'B.X': '35.15%',
'B.Y': '50.85%',
'C.X': '0.00%',
'C.Y': '0.00%',
'D.X': '14.00%',
'D.Y': '0.00%'}}
I would like to apply each dict1-key's total to my dict2 values of the same keys to get the ratio of total such as
dict3={'A': {'A.X': '3.06',
'A.Y': '4.59',
'B.X': '3.01',
'B.Y': '1.5',
'C.X': '1.2',
'C.Y': '1.63'},
'B': {'B.X': '4.92',
'B.Y': '7.12',
'C.X': '0',
'C.Y': '0',
'D.X': '1.96',
'D.Y': '0'}}
I thought I may start with
new_dict = { key : dict1[key]*dict2[key][0] for key in dict1 if key in dict2 }
but this didnt work. Any help is appreciated
p.s I am new to python and thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过两层迭代获得所需的结果:
You can get the result you want by two layers of iteration: