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?
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.
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: []} .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With