Create or append to a list in a dictionary - can this be shortened?

后端 未结 3 1646
忘掉有多难
忘掉有多难 2021-01-30 16:11

Can this Python code be shortened and still be readable using itertools and sets?

result = {}
for widget_type, app in widgets:
    if widget_type not in result:
         


        
3条回答
  •  無奈伤痛
    2021-01-30 16:22

    You can use a defaultdict(list).

    from collections import defaultdict
    
    result = defaultdict(list)
    for widget_type, app in widgets:
        result[widget_type].append(app)
    

提交回复
热议问题