dictionary - Python: How to extend the content of a list store in a dict? -
this question has answer here:
i facing simple , strange problem python.
i have dict several keys, contain empty lists. want append/extend content of lists of specific keys. code therefore think of looks this
d = dict.fromkeys(['a','b','c'],[]) d['a'].append('hello')
however, result not expect. value of each key list containing 1 element: 'hello'
>>> d {'a': ['hello'], 'c': ['hello'], 'b': ['hello']}
if try follows, results in same thing
d.get('a').append('bye')
what operations have obtain this?
>>> d {'a': ['hello'], 'c': [], 'b': []}
can explains goes wrong syntax?
your syntax fine, you're using same list on , on again. since lists mutable, when append
, you're adding 'hello' same list, happens referenced in 3 places. want instead create dict little more manually:
d = {k:[] k in ['a', 'b', 'c']}
(the above python 2.7 or later. older python can use: dict((k,[]) k in ['a', 'b', 'c'])
)
Comments
Post a Comment