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

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

This question is related to python

The answer is


May be some time this also will be helpful

import collections
#Write you select statement here and other things to fetch the data.
 if rows:
            JArray = []
            for row in rows:

                JArray2 = collections.OrderedDict()
                JArray2["id"]= str(row['id'])
                JArray2["Name"]= row['catagoryname']
                JArray.append(JArray2)

            return json.dumps(JArray)

Example Output:

[
    {
        "id": 14
        "Name": "someName1"
    },
    {
        "id": 15
        "Name": "someName2"
    }
]

To insert/append to a dictionary

{"0": {"travelkey":"value", "travelkey2":"value"},"1":{"travelkey":"value","travelkey2":"value"}} 

travel_dict={} #initialize dicitionary 
travel_key=0 #initialize counter

if travel_key not in travel_dict: #for avoiding keyerror 0
    travel_dict[travel_key] = {}
travel_temp={val['key']:'no flexible'}  
travel_dict[travel_key].update(travel_temp) # Updates if val['key'] exists, else adds val['key']
travel_key=travel_key+1

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 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.


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

If you want to add a new record in the form

newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']

to messageName where messageName in the form X_somemessage can, but does not have to be in your dictionary, then do it this way:

myDict.setdefault(messageName, []).append(newRecord)

This way it will be appended to an existing messageName or a new list will be created for a new messageName.


Add a key, value pair to dictionary

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.