Question:
I have some dictionary in python, and I want to assign a list as a value to each key in the dictionary, but I need to use the append() method to add elements, but after adding the elements to the list, the value of the key is None.
Ex:
dic = {}
lista = []
dic['a'] = lista.append('a')
print dic
{a:None}
How do I solve this problem?
Answer:
The append
method does not return a value, so its key has a value of None
. The correct way is as follows:
>>> dic = {}
>>> lista = []
>>> dic['a'] = lista
>>> lista.append('a')
>>> print dic
{'a': ['a']}
Or, if you prefer, this way is more direct:
>>> dic = {}
>>> dic['a'] = []
>>> dic['a'].append('a')
>>> print dic
{'a': ['a']}
>>>