Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more compact way to convert a sequence of (key,value) tuples into a {key:[value,..],..} dict?

I have a sequence of tuples itemList in the format (key, value) and I want to convert the items in that list into a dict in the format {key : [value, ..], ..}. A specific key value may appear in itemList multiple times with a matching or new value, and I want to record these values as well (which is why simply using dict(itemList) does not work).

I'm using Python2.7.9 and looking for ways to miniaturize this code:

newDict = dict()
for k,v in itemList:  # itemList contains the tuples described above.
    if k in newDict:
        newDict[k].append(v)
    else:
        newDict[k] = [v]

I've tried using map() and list-comprehensions in combination with newDict.update(..) but none have worked out as intended.

I've looked at this similar question, but the format of my inputs and desired output are considerably different.

(For those wondering, "Why would you want to change this perfectly acceptable code?": I'm interested in finding alternative ways of applying Python's built-ins and modules more as an academic exercise, rather than to purposefully avoid something functional and comprehensible.)

like image 372
Augusta Avatar asked Jan 02 '26 02:01

Augusta


1 Answers

You can use dict.setdefault to shorten your code, like this

newDict = {}
for k, v in itemList:
    newDict.setdefault(k, []).append(v)

The setdefault will look for the key in the dictionary, if it is not found it will assign the second parameter to it and return it.

If the key is found in the dictionary, it will simply return the corresponding value.


Alternatively, you can use collections.defaultdict, like this

from collections import defaultdict

result = defaultdict(list)
for k, v in itemList:
    result[k].append(v)

This is similar to the setdefault approach. If the key is not found in the dictionary, then the function passed to defaultdict constructor will be called to create a new value.

like image 92
thefourtheye Avatar answered Jan 03 '26 16:01

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!