将列表追加到字典中并进行更新
append list inside dictionary with update
如果我有以下字典,其中一个元素是列表,如下所示:
myDict = dict(a=1, b='2', c=[])
如何更新 myDict 并同时附加 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 值执行就地操作。改为尝试列表串联:
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'])
如果我有以下字典,其中一个元素是列表,如下所示:
myDict = dict(a=1, b='2', c=[])
如何更新 myDict 并同时附加 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 值执行就地操作。改为尝试列表串联:
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'])