Use list as dictionary value using append () method Python

4

I have some dictionary in python, and I want to assign a list as value for each key of the dictionary, however I need to use the append () method to add elements, but after adding the elements in 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?

    
asked by anonymous 20.06.2014 / 05:19

1 answer

5

The append method does not return value, so its key is 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']}
>>> 
    
20.06.2014 / 05:24