如何在Python 3中将字典追加到字典中?
有没有办法把一个字典添加到另一个字典里呢?我知道可以创建一个字典,里面包含其他字典:
father_dictionary={
'Dict1':{'a':'1','b':2,'c':3}
'Dict2':{'a':'4','b':5,'c':3}
}
mother_dictionary={
'Dict3':{'a':'6','b':7,'c':3}
但是如果我想把 Dict3
添加到 father_dictionary
里,假设 Dict3
是 mother_dictionary
里的一个键,该怎么做呢?
我试了很多方法,但总是遇到错误,提示我
'dict' 是一种不可哈希的类型,或者是语法错误。
3 个回答
0
首先,(我希望这只是复制粘贴的问题)你的语法是错误的。
字典里的元素是用逗号分开的。所以 father_dictionary
应该是:
father_dictionary = {
'Dict1':{'a':'1', 'b':2, 'c':3},
'Dict2':{'a':'4', 'b':5, 'c':3}}
另外,你在 mother_dictionary
里忘记关闭一个括号了:
mother_dictionary = {
'Dict3':{'a':'6', 'b':7, 'c':3}}
现在我们来看看问题,要解决你的问题,你可以试试使用字典里的 update()
方法:
father_dictionary.update(mother_dictionary)
2
来看这段代码:
>>> father_dictionary={
'Dict1':{'a':'1','b':2,'c':3},
'Dict2':{'a':'4','b':5,'c':3}
}
>>> mother_dictionary={
'Dict3':{'a':'6','b':7,'c':3}}
然后更新父字典:
>>> father_dictionary.update(mother_dictionary)
测试:
>>> father_dictionary.get('Dict3')
{'a': '6', 'b': 7, 'c': 3}
7
简单来说,要在已有的字典里添加一个键值对,你只需要把新的键当作下标,新的值放在等号的右边进行赋值就可以了:
parent_dictionary['Dict3'] = {'a':'7', 'b': 8, 'c': 9}
更新问题的编辑:
如果你想把两个字典合并,可以使用 update
方法。比如,如果你想把 mother_dictionary
中的所有键添加到 father_dictionary
中,可以这样做:
father_dictionary.update(mother_dictionary)
如果你只想添加一个 单独的 键(而你的问题还没有明确是要添加一个键还是所有键),同样可以使用赋值的方法:
father_dictionary['Dict3'] = mother_dictionary['Dict3']