用更新在字典内追加列表 [英] append list inside dictionary with update

查看:44
本文介绍了用更新在字典内追加列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我下面的词典中的元素之一是列表,则如下所示:

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

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

如何更新myDict并同时附加c

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

例如

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

,最终结果应该是:

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

在一个声明中....

推荐答案

您不能在update中使用append,因为append试图对dict值执行就地操作.尝试使用列表串联:

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

或者:

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

这篇关于用更新在字典内追加列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆