Search code examples
pythondictionarynestedkey

How to compare dictionaries and calculate a ratio based on their keys and values


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.


Solution

  • 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'}}