How to create lists are automatically created when used in Python, as in Perl?

In Perl, I can do this:

push(@{$h->[x]}, y); 

Is it possible to simplify the following python codes according to the Perl example above?

 if x not in h: h[x] = [] h[x].append(y) 

I want to simplify this because it has many places in my code (and I cannot initialize all possible x with []). I do not want to make it a function because the keyword "inline" is missing.

Any ideas?

+4
source share
3 answers

A very elegant way (since Python 2.5) is to use the defaultdict from the collections module:

 >>> from collections import defaultdict >>> h = defaultdict(list) >>> h['a'].append('b') >>> h defaultdict(<type 'list'>, {'a': ['b']}) 

defaultdict is like a dict, but provides a default value using any constructor that you passed to it when you created it (in this example, a list).

I especially like this with the setdefault dict method, because 1) you define the variable as defaultdict, and in general no other changes are required for the code (except, perhaps, to remove previous kludges for default values); and 2) setdefault - scary name: P

+9
source

There are several ways to do this using the dict methods :

 h.setdefault(x, []).append(y) 

or

 h[x] = h.pop(x,[]).append(y) 
+4
source

You can use setdefault

 h = {} h.setdefault(x, []).append(y) 
+3
source

Source: https://habr.com/ru/post/1308202/


All Articles