简体   繁体   中英

Pythonic way of adding items to a dict of lists

I use this snippet pretty often:

d = {}
for x in some_list:
    y = some_func(x)  # can be identity 
    if y in d:
        d[y].append(another_func(x))
    else:
        d[y] = [another_func(x)]

Is this the most pythonic way of doing this or there's a better way? I use Python 3.

you can try

from collections import defaultdict

d = defaultdict(list)
for x in some_list:
    d[some_func(x)].append(another_func(x))

The defaultdict is a dictionary option that you init it with the type that you would like to assign in case the key that you are looking for not exists in the keys of the dictionary. In this case, each time that you will call d if the key doesn't exist it will create an empty list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM