如何添加键,值对到字典?

如何添加键,值对字典? 下面我提到了以下格式?

{'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']]}
430038 次浏览

向 dictionary 中添加键值对

aDict = {}
aDict[key] = value

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

我不知道你说的“活力”是什么意思。如果您指的是在运行时将条目添加到字典中,那么它与 dictionary[key] = value一样简单。

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

dictionary[key] = value

如果要在窗体中添加新记录

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)

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

也许有一段时间这也会有所帮助

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)

示例输出:

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

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

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

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

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)

您还可以混合使用它们,例如,如果键“ c”在数据中,而“ d”不在数据中,则下面的方法将更新“ c”并添加“ d”

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

To 插入/附加 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