-1

I have a multidimensional dictionary to which I am unable to add a new element. Can you please help with this query :

items = {'Warner': {'balls': 4, 'runs': 6},
         'Dhawan': {'balls': 2, 'runs': 0},
         'yuvaraj': {'balls': 1.5, 'runs': 32},
         'scouts': {'balls': 3, 'runs': 15}
        }

to this, I want to add a new element

items['varun'] = [{'balls': 2}, {'runs': 2}]

However, the above line throws an error saying key error Varun.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
  • 2
    Are you sure you are not missing something? I don't see anything would throw that error and it does work in my python, both 2 and 3. – Yang Mar 02 '18 at 17:18
  • Please include all of the relevant code and the complete traceback in the question. – Keyur Potdar Mar 02 '18 at 17:21
  • Possible duplicate of [Add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary) – baduker Mar 02 '18 at 17:27

1 Answers1

1

In your first piece

 `items = {'Warner': {'balls': 4,   'runs': 6 },
         'Dhawan':  {'balls': 2,   'runs': 0 },
          'yuvaraj': {'balls': 1.5, 'runs': 32},
          'scouts':   {'balls': 3,   'runs': 15},
        }`

you've got a dict matched to a key, but then you are trying to match a list of dict, instead of just dict. Try this:

items['varun']  = {'balls':2 , 'runs' : 2}

Output:

{'Warner': {'balls': 4, 'runs': 6},
 'Dhawan': {'balls': 2, 'runs': 0},
 'yuvaraj': {'balls': 1.5, 'runs': 32},
 'scouts': {'balls': 3, 'runs': 15}, 
 'varun': {'balls': 2, 'runs': 2}}
Anthony
  • 421
  • 1
  • 5
  • 13