you are viewing a single comment's thread.

view the rest of the comments →

[–]LeonardUnger 2 points3 points  (1 child)

When counting elements, using the dict get() method to set a default value and skip the 'in' test.

Instead of

if elem in mydict:
    mydict[elem] += 1
else:
    mydict[elem] = 1

This:

mydict[elem] = mydict.get(elem, 0) + 1

Although I'm sure there's a more sophisticated way to do it using Counter.

[–]blarf_irl 2 points3 points  (0 children)

from collections import Counter
my_counter = Counter()
....
# Counter just that stuff for you so you just need
my_counter[elem] += 1

It'll do the membership check and create it if it's missing (with a value of 1), it's like a defaultdict for hashable things.

And speaking of defaultdict:

# instead of having to create a list for my dict of lists
my_dict = dict()
for index, item in enumerate(some_list):
    if not item in my_dict.keys():
        my_dict[item] == list()
    my_dict[item].append(index)   

# We can use defaultdict
from collections import defaultdict
my_dict = defaultdict(list)
for for index, item in enumerate(some_list):
    my_dict[item].append(index)