Creating a dict from list of key, value tuples while maintaining duplicate keys

前端 未结 3 702
情书的邮戳
情书的邮戳 2020-12-03 14:42

So I\'ve got a comprehension to the effect of:

dict((x.key, x.value) for x in y)

The problem, of course, is that if there\'s multiple

相关标签:
3条回答
  • 2020-12-03 15:08

    You can add the elements one by one to a dictionary that contains empty lists by default:

    import collections
    
    result_dict = collections.defaultdict(list)
    for x in y:
        result_dict[x.key].append(x.value)
    

    You can also do something very similar without having to use the collections module:

    result_dict = {}
    for x in y:
        result_dict.setdefault(x.key, []).append(x.value)
    

    but this is arguably slightly less legible.

    An equivalent, more legible (no need to "parse" the less common setdefault) but more pedestrian, base Python approach is:

    result_dict = {}
    for x in y:
        if x.key not in result_dict:
            result_dict[x.key] = []
        result_dict[x.key].append(x.value)
    

    The first solution is clearly the preferred one, as it is at the same time concise, legible, and fast.

    0 讨论(0)
  • 2020-12-03 15:20

    I'm not saying it's the right thing to do, but, just out of sheer intellectual curiosity..

    You can use itertools.groupby and lambda to do it in one dict comprehension, if that's what you really want to do: (where l is the list of tuples you want to make a dict out of:

    dict((k, [v[1] for v in vs]) for (k, vs) in itertools.groupby(l, lambda x: x[0]))
    
    0 讨论(0)
  • 2020-12-03 15:24

    Nope. You cannot do this in a comprehension.

    But you can use itertools.groupby.

    0 讨论(0)
提交回复
热议问题