0

I have a dictionary as follows:

mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
 'branch': {'NumberOfTimes': 4, 'Score': 34},
 'transfer': {'NumberOfTimes': 1, 'Score': 5},
 'deal': {'NumberOfTimes': 1, 'Score': 10}}

I want to divide the Score by NumberOfTimes for each key in mydict, and save it in either a list or another dictionary. The goal is to have the following:

newdict = {word:'HEALTH', 'AvgScore': 6},
 {word:'branch': 4, 'AvgScore': 8.5},
 {word:'transfer', 'AvgScore': 5},
 {word:'deal', 'AvgScore': 10}}

My code for the latter is as follows:

newdict = {}
for k, v in mydict.items():
    newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']

But this gives the error KeyError: 'HEALTH'.

I tried the following as well:

from collections import defaultdict
newdict = defaultdict(dict)

for k, v in mydict.items():
    newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']

Here I get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-237-d6ecaf92029c> in <module>()
      4 # newdict = {}
      5 for k, v in mydict.items():
----> 6     newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']
      7 
      8 #sorted(newdict.items())

TypeError: string indices must be integers

How do I add the key-value pairs into a new dictionary?

Kristada673
  • 3,512
  • 6
  • 39
  • 93
  • replace `for k, v in word_vec.items():` with `for k, v in mydict.items():` – Sociopath Jul 05 '18 at 09:38
  • for first error `KeyError: 'HEALTH'`, try to use `update` to add new key, and if you have nested dicts, you should add all levels by `youdict.update`. – mortymacs Jul 05 '18 at 09:39
  • The problem is your try to set a nested dict like `newdict[k]['AvgScore']`. See [this post](https://stackoverflow.com/questions/13687924/setting-a-value-in-a-nested-python-dictionary-given-a-list-of-indices-and-value) for ways to achieve that kind of behavior. – vahdet Jul 05 '18 at 09:44

2 Answers2

1

Using a simple iteration.

Demo:

mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
 'branch': {'NumberOfTimes': 4, 'Score': 34},
 'transfer': {'NumberOfTimes': 1, 'Score': 5},
 'deal': {'NumberOfTimes': 1, 'Score': 10}}

newdict = {}
for k, v in mydict.items():
    newdict[k] = {"word": k, 'AvgScore': v['Score']/v['NumberOfTimes']}
print(newdict.values())

Output:

[{'word': 'transfer', 'AvgScore': 5}, {'word': 'HEALTH', 'AvgScore': 6}, {'word': 'branch', 'AvgScore': 8}, {'word': 'deal', 'AvgScore': 10}]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • In my actual dictionary (I only showed the first 4 key-value pairs in it, but it has some thousands), I get the following error with your code: `TypeError: string indices must be integers` on the line `word_vec_avg[k] = {"word": k, 'AvgScore': v['Score']/v['NumberOfTimes']}` – Kristada673 Jul 05 '18 at 09:51
  • Yes. In fact, when I just copy the first 4 entries in `mydict` as here, there's no error. The error only comes when taking the full dictionary. – Kristada673 Jul 05 '18 at 10:04
  • Looks like you have a list in your dict. Please check your dict values – Rakesh Jul 05 '18 at 10:08
1

Try this:

mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
 'branch': {'NumberOfTimes': 4, 'Score': 34},
 'transfer': {'NumberOfTimes': 1, 'Score': 5},
 'deal': {'NumberOfTimes': 1, 'Score': 10}}

word_vec_avg = {}
for k, v in mydict.items():
        word_vec_avg[k]={'AvgScore':v['Score']/v['NumberOfTimes']} #create a new dict and assign
Dan
  • 45,079
  • 17
  • 88
  • 157
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
  • In my actual dictionary (I only showed the first 4 key-value pairs in it, but it has 2596 key-value pairs), I get the following error with your code: `TypeError: string indices must be integers` on the line `word_vec_avg[k] = {"word": k, 'AvgScore': v['Score']/v['NumberOfTimes']}`, although when I try to print the new dictionary, I see that it contains 2404 items. – Kristada673 Jul 05 '18 at 09:54