Shelina
Shelina

Reputation: 103

How to replace dict values with new values

I have a dictionary that looks like:

the 117
to 77
. 77
, 56
a 47
is 46
and 41
that 39
...

I wanted to divide each number in the dictionary by the max value.. so I did this:

count_values = (count.values())
newValues = [x / max(count_values) for x in count_values]

I want to replace the values in the dictionary with newValues.

How can I do that?

Upvotes: 1

Views: 358

Answers (2)

abarnert
abarnert

Reputation: 365717

First, you probably don't want to compute max(count_values) over and over for each element, so do that once up-front:

max_value = max(count.values())

Now, if you actually need to modify the dict in-place, do it like this:

for key in count:
   count[key] /= max_value

However, if you don't need to do that, it's usually cleaner to make a new dict via a comprehension, as in Haleemur Ali's great answer:

count = {key: value / max_value for key, value in count.items()}

Upvotes: 0

Haleemur Ali
Haleemur Ali

Reputation: 28253

Try using dictionary comprehension.

old_values = {'the': 117, 'to': 77, '.': 77, ',': 56, 'a': 46, 'is': 46, 'and': 41, 'that': 39}
m = max(old_values.values())
new_values = {k: v / m for k, v in old_values.items()}

This produces a dictionary like this:

{'the': 1.0, 
 'to': 0.6581196581196581, 
 '.': 0.6581196581196581, 
 ',': 0.47863247863247865, 
 'a': 0.39316239316239315, 
 'is': 0.39316239316239315, 
 'and': 0.3504273504273504, 
 'that': 0.3333333333333333}

Upvotes: 3

Related Questions