Python 如何将键值对添加到字典中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3776275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add key,value pair to dictionary?
提问by Krishnasamy
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']]}
回答by pyfunc
Add a key, value pair to dictionary
将键值对添加到字典
aDict = {}
aDict[key] = value
What do you mean by dynamic addition.
动态加法是什么意思。
回答by Manoj Govindan
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.
我不确定你所说的“动态”是什么意思。如果您的意思是在运行时将项目添加到字典中,那么就像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
回答by eumiro
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 messageNamewhere messageNamein the form X_somemessagecan, but does not have to be in your dictionary, then do it this way:
到messageName那里messageName的形式X_somemessage也可以,但并不一定要在你的字典里,然后做这种方式:
myDict.setdefault(messageName, []).append(newRecord)
This way it will be appended to an existing messageNameor a new list will be created for a new messageName.
这样,它将被附加到现有的messageName或为新的messageName.
回答by Abhilash Cherukat
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"
}
]
回答by domoarigato
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] = valuewould 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)))
在这种情况下,您可以使用更新方法:
dictionary.update(function_that_returns_a_dict(*args, **kwargs)))
Beware, if dictionaryalready contains one of the keys, the original value will be overwritten.
请注意,如果dictionary已经包含其中一个键,则原始值将被覆盖。
回答by Zhenhua
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'
您也可以将它们混合起来,例如,如果键 'c' 在数据中而 'd' 不在,则以下方法将更新 'c' 并添加 'd'
data.update({'c':3,'d':4})
回答by Jose Kj
To insert/appendto 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

