append list inside dictionary with update

做~自己de王妃 提交于 2019-12-13 02:01:02

问题


if i have below dictionary with one of the element is list, as follow:

myDict = dict(a=1, b='2', c=[])

how do I update myDict and at the same time append c

e.g.

myDict .update(a='one', b=2, c=append('newValue'))
myDict .update(a='1', b='two', c=append('anotherValue'))

and the final result should be:

myDict = a='1', b='two', c=['newValue', 'anotherValue']

in one statement....


回答1:


You can't use append within update because append is trying to perform an inplace operation on the dict value. Try list concatenation instead:

d = dict(a=1, b='2', c=[])
d.update(a='one', b=2, c=d['c'] + ['newValue'])
print(d)
{'a': 'one', 'b': 2, 'c': ['newValue']}

Or:

d.update(a='one', b=2, c=d['c'] + ['newValue'] + ['anotherValue'])


来源:https://stackoverflow.com/questions/46119860/append-list-inside-dictionary-with-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!