0

I have the following code to create a dictionary whose elements are lists from another dictionary:

olddict={'Fiesta': {'key':'Ford'},'Golf': {'key':'Volkswagen'}, 'Bora': {'key':'Volkswagen'} }
newdict = {}
for key, value in olddict.items():
    newkey = value['key']
    if newkey in newdict:
        newdict[newkey].append(key)
    else:
        newdict[newkey] = [key]

The code works fine, but seems utterly non-pythonic. Maybe I am a bit tired, but a one-line solution would be great...

2 Answers 2

2

Use defaultdict():

>>> olddict={'Fiesta': {'key':'Ford'},'Golf': {'key':'Volkswagen'}, 'Bora': {'key':'Volkswagen'} }
>>> from collections import defaultdict

>>> result = defaultdict(list)
>>> for k, v in olddict.items():
...     result[v['key']].append(k)
...

>>> result
defaultdict(<type 'list'>, {'Ford': ['Fiesta'], 'Volkswagen': ['Golf', 'Bora']})

This method initializes an empty list when a new key is found. Essentially getting rid of the else part in your code. I am not sure you can combine a defaultdict with list comprehension to make it a one-liner.

Sign up to request clarification or add additional context in comments.

Comments

0

Using itertools.groupby.

from itertools import groupby as g
keyfunc = lambda x: olddict[x]['key']
newdict = dict( (k, list(vs)) for k, vs in g(sorted(olddict, key=keyfunc), keyfunc))

If you are using Python 2.7 or later, you can also use a dict comprehension

newdict = { k: list(vs) for k, vs in g(sorted(olddict, key=keyfunc), keyfunc) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.