问题
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