python dict: get vs setdefault

前端 未结 8 1093
误落风尘
误落风尘 2020-12-04 15:04

The following two expressions seem equivalent to me. Which one is preferable?

data = [(\'a\', 1), (\'b\', 1), (\'b\', 2)]

d1 = {}
d2 = {}

for key, val in d         


        
8条回答
  •  星月不相逢
    2020-12-04 15:53

    You might want to look at defaultdict in the collections module. The following is equivalent to your examples.

    from collections import defaultdict
    
    data = [('a', 1), ('b', 1), ('b', 2)]
    
    d = defaultdict(list)
    
    for k, v in data:
        d[k].append(v)
    

    There's more here.

提交回复
热议问题