如何向字典中添加键、值对?

时间:2021-09-05 20:05:41

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

7 个解决方案

#1


85  

Add a key, value pair to dictionary

向字典添加一个键,值对

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.

你说的动态加法是什么意思?

#2


19  

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:

对于快速引用,所有以下方法将添加一个新键'a',如果它不存在,或者它将更新现有的键值对,并提供新的值:

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'

你也可以把它们混合起来,例如,如果key 'c'在数据中,而'd'不是,下面的方法会更新'c'并添加'd'

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

#3


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

我在这里寻找将键/值对作为组添加的方法——在我的例子中,它是函数调用的输出,因此使用dictionary[key] = value添加键/值对需要知道键的名称。

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

在这种情况下,您可以使用update方法:dictionary。更新(function_that_returns_a_dict(* args,* * kwargs)))

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

注意,如果字典已经包含其中一个键,那么原始值将被覆盖。

#4


6  

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.

我不知道你所说的“动态”是什么意思。如果你想在运行时向字典中添加条目,那么它就像字典[key] =值一样简单。

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

如果您希望创建一个带有键的字典,那么从value开始(在编译时),然后使用(惊讶!)

dictionary[key] = value

#5


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:

对于messageName, X_somemessage表单中的messageName可以,但不需要出现在字典中,然后这样做:

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.

这样,它将被追加到一个现有的messageName中,或者为一个新的messageName创建一个新的列表。

#6


1  

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

#7


-1  

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

#1


85  

Add a key, value pair to dictionary

向字典添加一个键,值对

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.

你说的动态加法是什么意思?

#2


19  

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:

对于快速引用,所有以下方法将添加一个新键'a',如果它不存在,或者它将更新现有的键值对,并提供新的值:

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'

你也可以把它们混合起来,例如,如果key 'c'在数据中,而'd'不是,下面的方法会更新'c'并添加'd'

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

#3


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

我在这里寻找将键/值对作为组添加的方法——在我的例子中,它是函数调用的输出,因此使用dictionary[key] = value添加键/值对需要知道键的名称。

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

在这种情况下,您可以使用update方法:dictionary。更新(function_that_returns_a_dict(* args,* * kwargs)))

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

注意,如果字典已经包含其中一个键,那么原始值将被覆盖。

#4


6  

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.

我不知道你所说的“动态”是什么意思。如果你想在运行时向字典中添加条目,那么它就像字典[key] =值一样简单。

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

如果您希望创建一个带有键的字典,那么从value开始(在编译时),然后使用(惊讶!)

dictionary[key] = value

#5


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:

对于messageName, X_somemessage表单中的messageName可以,但不需要出现在字典中,然后这样做:

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.

这样,它将被追加到一个现有的messageName中,或者为一个新的messageName创建一个新的列表。

#6


1  

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

#7


-1  

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