113

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']]}
Krishnasamy
  • 1,155
  • 2
  • 7
  • 4

7 Answers7

161

Add a key, value pair to dictionary

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.

pyfunc
  • 65,343
  • 15
  • 148
  • 136
  • Thanks it's working..I meant resultset of query. Do you know which are the concerns using python..i don't know am new of this technology before i have worked in dotnet. – Krishnasamy Sep 23 '10 at 08:19
  • 2
    @Krishnasamy: If you have earlier worked on dotnet, Python will be a pleasure to work with. It is as versatile as dotnet and java, if not more – pyfunc Sep 23 '10 at 08:23
  • 1
    If I use this in for loop than its giving only last record.. how to get all key value pair in loop – Vijaysinh Parmar Jul 26 '19 at 09:01
82

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})  
Zhenhua
  • 2,389
  • 15
  • 10
  • 2
    Why is the down vote? The answer is trying to add useful info so viewers can have an alternative answer which IMHO is more comprehensive, could the gentleman/women who down voted pls clarify? – Zhenhua Aug 07 '17 at 20:58
  • You don't need to answer this question since its a duplicate - the appropriate way of handling it is by flagging it as a dupe - see more info there [How should duplicate questions be handled?](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled) – Igor B Aug 13 '17 at 14:18
  • 9
    @Zhenhua I found this answer useful upvoted. – Shek Oct 03 '17 at 16:09
  • 4
    This answer is much more helpful than the other ones. – Pinaki Mukherjee Mar 10 '18 at 14:36
  • 3
    SO really needs to figure out a way to make things surface better. This is down voted for being a duplicate. But it's the first thing that appears when a user searches. The down vote then starts more conversation, which causes this answer to FURTHER rise in popularity, thereby hiding the original answer. I would have never have found the original answer had this one not existed. So why not just delete this qeustion completely? – Dave Voyles Jul 12 '18 at 18:47
  • I think what would have made this a truly useful answer would be a discussion of the differences in the different statements - is one preferred for a given use case? Are they all the same? Any pitfalls to any of them? – Michael Jay Sep 24 '20 at 01:14
9

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
Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
7

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.

domoarigato
  • 2,802
  • 4
  • 24
  • 41
4

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"
    }
]
xinthose
  • 3,213
  • 3
  • 40
  • 59
3

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.

eumiro
  • 207,213
  • 34
  • 299
  • 261
-2

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
Jose Kj
  • 2,912
  • 2
  • 28
  • 40