1

I have two dicts:

dict_1 = {'A': ['red', 'red', 'blue'],
          'B': ['red', 'green'],
          'C': ['blue', 'green'], ....}

dict_2 = {'A': Counter({'red': 2, 'blue': 1}),
          'B': Counter({'red': 1, 'green': 1}),
          'C': Counter({'blue': 1, 'green': 1}), ....}

I need to do some simple division between them and later plot them pairwise. The desired outcome is like this or anything that can do the division:

fraction = {'A': [2/3, 1/3],
            'B': [1/2, 1/2],
            'C': [1/2, 1/2], ....} 

Right now, I can only get the first digit divided, any advice will be appreciated! Here's my code:

fraction = { key: [v/len(colorz)] for namez, colorz in dict_1.items() 
                          for name, color in dict_2.items() 
                          for k, v in color.items() }
martineau
  • 119,623
  • 25
  • 170
  • 301
Alex
  • 63
  • 6
  • Do you want those fractions as strings? Also, `dict_1` and `dict_2` are just different expressions of the same data, right? – brunns Apr 28 '19 at 17:12
  • No, I don't want those fractions as strings. Yes, dict_1 and dict_2 have the same key but dict_2 counted the frequencies of dict_1 values. – Alex Apr 29 '19 at 05:17

2 Answers2

4

.count is pretty fast, so I am not using dict_2 with the Counter, but it is fine to use it.

fraction = {k: [l.count(e)/len(l) for e in set(l)] for k, l in dict_1.items()}

but this is meant to be short not necessarily efficient. If it needs to be faster, you can do something else. if you want them as strings then

fraction = {k: [f'{e.count(l)}/{len(l)}' for e in set(l)] for k, l in dict_1.items()}

and if you want them as strings of reduced fractions use the fraction module

modesitt
  • 7,052
  • 2
  • 34
  • 64
  • 1
    It's great, but there must be l.count(e). And if the key is 'B' the result is [1/2] and not [1/2,1/2]. – kantal Apr 28 '19 at 18:36
2

A version using Fractions.

from fractions import Fraction
{k: [Fraction(v[i], sum(v.values())) for i in v] for k, v in dict_2.items()}
brunns
  • 2,689
  • 1
  • 13
  • 24