|
|
|
|
|
by balbeit
5390 days ago
|
|
I always love learning little tidbits about Python like these. Thanks! Another I found quite useful: instead of collections.defaultdict, you can use the dict's get() method to set a default value if the key doesn't exist. get() takes the key and a default value, and if the key doesn't exist it creates one with the default value provided. a = {}
a['foo'] = a.get('foo',0) + 1
# a = {'foo':1}
a['foo'] = a.get('foo',0) + 1
# a = {'foo':2}
It can be very useful for incrementing keys in a dict, even if they did not exist previously. |
|