Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list as the default value for a dictionary? [duplicate]

I have a Python code that looks like:

if key in dict:   dict[key].append(some_value) else:   dict[key] = [some_value] 

but I figure there should be some method to get around this 'if' statement. I tried:

dict.setdefault(key, []) dict[key].append(some_value) 

and

dict[key] = dict.get(key, []).append(some_value) 

but both complain about "TypeError: unhashable type: 'list'". Any recommendations?

like image 419
Fysx Avatar asked Jul 19 '13 21:07

Fysx


People also ask

How do I change the default value in a dictionary?

Python Dictionary setdefault() Method Syntax: Parameters: It takes two parameters: key – Key to be searched in the dictionary. default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.

How do you initialize a dictionary list?

To initialize a dictionary of empty lists in Python, we can use dictionary comprehension. to create a dictionary with 2 entries that are both set to empty lists as values. Therefore, data is {0: [], 1: []} .

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do you set a value in a dictionary in a way that doesn't override existing values?

setdefault will precisely "set a value in a dict only if the value is not already set". dict. setdefault() is designed to be used when you are effectively fetching the value for a key, where you want to ensure the key exists, always. Using it as a setter only goes counter to normal use.


1 Answers

The best method is to use collections.defaultdict with a list default:

from collections import defaultdict dct = defaultdict(list) 

Then just use:

dct[key].append(some_value) 

and the dictionary will create a new list for you if the key is not yet in the mapping. collections.defaultdict is a subclass of dict and otherwise behaves just like a normal dict object.

When using a standard dict, dict.setdefault() correctly sets dct[key] for you to the default, so that version should have worked just fine. You can chain that call with .append():

>>> dct = {} >>> dct.setdefault('foo', []).append('bar')  # returns None! >>> dct {'foo': ['bar']} 

However, by using dct[key] = dct.get(...).append() you replace the value for dct[key] with the output of .append(), which is None.

like image 80
Martijn Pieters Avatar answered Oct 13 '22 11:10

Martijn Pieters