Alex Rivera | Logout

How can I add new keys to a dictionary?

Asked 2009-06-21T22:07:39.587
3600

How do I add a new key to an existing dictionary? It doesn't have an .add() method.

Edit
Report

1 Answer

48

You can create one:

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        self[key] = value

## example

myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)

Gives:

>>> 
{'apples': 6, 'bananas': 3}
answered 2013-05-25T13:33:35.353

Your Answer