Kristada673
Kristada673

Reputation: 3744

How do I insert new items in a blank dictionary in Python 3?

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?

Upvotes: 0

Views: 108

Answers (2)

Rakesh
Rakesh

Reputation: 82765

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}]

Upvotes: 1

Taohidul Islam
Taohidul Islam

Reputation: 5414

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

Upvotes: 1

Related Questions