0

I have defined a dictionary as

coocurences = {('a', 'b'): 74, ('a', 'c'): 33, ('b', 'c'): 26}

and I would like to change the values of this dictionary into proportions of the sum of its values:

{('a', 'b'): 0,556390977443609‬, ('a', 'c'): 0,2481203007518797, ('b', 'c'): 0,1954887218045113‬‬}

I have tried with:

for x in coocurences.values():
    x = (x/sum(coocurences.values()))

but it tells me: TypeError: 'builtin_function_or_method' object is not iterable. Any suggestions how to accomplish this?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Are you sure the code you posted results in that error? Seems like you would get that error from doing `for x in coocurences.values:` (without the parentheses). – Henry Woody Mar 16 '20 at 18:53
  • You are right. I forgot the parentheses in the code. I get no Error when added but also not the anticipated result. Thanks for pointing out. – Johannes Jamrosz Mar 16 '20 at 18:58

2 Answers2

4

There are a couple of problems with the code you presented:

  1. the code you posted doesn't throw any errors (I think in your actual code you might've had for x in coocurences.values without any parentheses, which would throw an error).

  2. x is only a copy of the values in the dictionary. Changing x won't change the values in the dict. See Can't modify list elements in a loop Python .

  3. if you're changing the values during the loop, the sum you compute will also change. It's also less efficient to compute the sum every so you might as well compute it before the loop.

Putting it all together:

total = sum(coocurences.values())
for k,v in coocurences.items():
    coocurences[k] = v/total

Better yet, use a dict comprehension:

total = sum(coocurences.values())
answer = {k: v/total for k,v in coocurences.items()}
Jay Mody
  • 3,727
  • 1
  • 11
  • 27
  • would there be a way to make this dictionary a list like (('a', 'b', 0.556390977443609‬), ...)? – Johannes Jamrosz Mar 16 '20 at 19:10
  • @JohannesJamrosz `answer = [k+(v/total,) for k,v in coocurences.items()]`. I'd recommend you learn more about list comprehensions. You can pretty much transform you're data however you want with them. Not only is it very pythonic, but it also is more efficient and uses less lines of code. – Jay Mody Mar 16 '20 at 19:13
  • grandiose. Thanks alot. I will do so. – Johannes Jamrosz Mar 16 '20 at 19:19
0

There is another way to do this. Rather then using ".values()" you can use the key to change the value, if that makes sense.

    for x in coocurences:
        coocurences[x] = (coocurences[x]/sum([coocurences[i] for i in coocurences]))
elliott
  • 11