如何根据其键和值比较字典并计算一个比率

发布于 2025-01-30 00:46:55 字数 857 浏览 4 评论 0原文

我有一个字典

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巨坚强 2025-02-06 00:46:55

您可以通过两层迭代获得所需的结果:

>>> dict3 = {}
>>> for k1, v1 in dict2.items():
...     total = int(dict1[k1][0]) / 100
...     dict3[k1] = {k2: f'{float(v2[:-1]) * total:.3g}' for k2, v2 in v1.items()}
...
>>> dict3
{'A': {'A.X': '3.06', 'A.Y': '4.59', 'B.X': '3.01', 'B.Y': '1.5', 'C.X': '1.21', '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'}}

You can get the result you want by two layers of iteration:

>>> dict3 = {}
>>> for k1, v1 in dict2.items():
...     total = int(dict1[k1][0]) / 100
...     dict3[k1] = {k2: f'{float(v2[:-1]) * total:.3g}' for k2, v2 in v1.items()}
...
>>> dict3
{'A': {'A.X': '3.06', 'A.Y': '4.59', 'B.X': '3.01', 'B.Y': '1.5', 'C.X': '1.21', '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'}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文