0

I have two dictionaries, one was populated from a dataset, the other I created manually. I was trying to do a bit of math on them, and store the results in another dictionary. It worked in an online platform, but when I run the Jupyter notebook using PyCharm, it will not return the correct results. Any idea why?

Here is the creation of the two dictionaries, and the output of the two of them (i.e., the content of the dictionaries)

race_counts = {}
    for race in race:
        if race not in race_counts:
            race_counts[race] = 1
        else:
            race_counts[race] += 1

mapping = {
'Asian/Pacific Islander': 15159516 + 674625,
'Native American/Native Alaskan': 3739506,
'Black': 40250635,
'Hispanic': 44618105,
'White': 197318956
}

race_counts dictionary:

{'Native American/Native Alaskan': 917,
 'Black': 23296,
 'White': 66237, 
 'Asian/Pacific Islander': 1326,
 'Hispanic': 9022}

mapping dictionary:

{'Native American/Native Alaskan': 3739506,
 'Black': 40250635,
 'White': 197318956,
 'Asian/Pacific Islander': 15834141,
 'Hispanic': 44618105}

Here is the math I'm trying:

race_per_hundredk = {}
for race in race_counts:
    race_per_hundredk[race] = (race_counts[race] / mapping[race]) * 100000
print(race_per_hundredk)

Now, the correct output I'm expecting is this:

{'Asian/Pacific Islander': 8.374309664161762,
 'Black': 57.8773477735196,
 'Hispanic': 20.220491210910907,
 'Native American/Native Alaskan': 24.521955573811088,
 'White': 33.56849303419181}

But, Instead I am getting this:

{'Native American/Native Alaskan': 0,
 'Asian/Pacific Islander': 0
 'White': 0, 
 'Black': 0,
 'Hispanic': 0}

The order of the keys doesn't matter but I'm not sure why the values are being returned empty.

Thanks a bunch, guys/gals. I swear I'll start answering some questions and giving back when I have an idea about what I'm doing...

lucretiuss
  • 75
  • 1
  • 7

1 Answers1

0

Try float casting:

race_per_hundredk = {}
for race in race_counts:
    race_per_hundredk[race] = (race_counts[race] / float(mapping[race])) * 100000
print(race_per_hundredk)
SatanDmytro
  • 537
  • 2
  • 7
  • That did the trick. Thank you! Do you have an insight into why I needed to specify that the keys in mapping were a float? I'm not sure why I needed to do it there. – lucretiuss Dec 19 '17 at 19:33
  • If you expect `float` result, you need apply this trick, because `int` division return result with `int` type(works like quotient in modulo operation) – SatanDmytro Dec 19 '17 at 19:40
  • Awesome, thank you! – lucretiuss Dec 19 '17 at 20:07