How to add key,value pair to dictionary? [duplicate]

How to add key,value pair to dictionary?.Below i have mentioned following format?

{'1_somemessage': [[3L,
                    1L,
                    u'AAA',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'gffggf'],
                   [3L,
                    1L,
                    u'BBB',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 20, 30),
                    u'ffgffgfg'],
                   [3L,
                    1L,
                    u'CCC',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'hjhjhjhj'],
                   [3L,
                    1L,
                    u'DDD',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 21, 45),
                    u'jhhjjh']],
 '2_somemessage': [[4L,
                    1L,
                    u'AAA',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'gffggf'],
                   [4L,
                    1L,
                    u'BBB',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 20, 30),
                    u'ffgffgfg'],
                   [4L,
                    1L,
                    u'CCC',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 22, 30),
                    u'hjhjhjhj'],
                   [4L,
                    1L,
                    u'DDD',
                    1689544L,
                    datetime.datetime(2010, 9, 21, 21, 45),
                    u'jhhjjh']]}

Add a key, value pair to dictionary

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.


For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:

data['a']=1  

data.update({'a':1})

data.update(dict(a=1))

data.update(a=1)

You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'

data.update({'c':3,'d':4})  

I am not sure what you mean by "dynamic". If you mean adding items to a dictionary at runtime, it is as easy as dictionary[key] = value.

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

dictionary[key] = value

I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value would require me to know the name of the key(s).

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.