Use list as dictionary value using Python append() method

Asked

Viewed 11,827 times

6

I have some python dictionary, and I want to assign a list as a value for each dictionary key, but I need to use the append() method to add elements, but after adding the elements to the list, the key value is None.

Ex:

dic = {}
lista = []
dic['a'] = lista.append('a')
print dic

{a:None}    

How do I solve this problem ?

3 answers

7


The method append does not return value, so its key has as value 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']}
>>> 

0

>>> dic = {}
>>> lis = [1, 2, 3]
>>> dic['num'] = lis[:] #criando cópia não gera vinculo com a lista
>>> print(dic)

{'num': [1,2,3]}

0

As already explained the method append() does not return value and therefore on the line:

dic['a'] = lista.append('a')

The key dic['a'] is assigned as None.

If all the values in your dictionary are lists, the module Collections includes specialized container subclasses that facilitate coding.
The class defaultdict is a subclass of dict calling a Factory function to provide the values not found.

In the example is passed the constructor reference list() as Factory function for defaultdict:

from collections import defaultdict

dic = defaultdict(list)
dic['a'].append('a')
dic['a'].append('b')
dic['a'].append('c')

print(dic)
#defaultdict(<class 'list'>, {'a': ['a', 'b', 'c']})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.