Dictionary comprehension with list comprehension as values

Viewed 28

I'm fairly certain the solution to this wouldn't be pythonic at all, but I'm curious to see how one would actually go about doing it. Assuming I have data that looks like:

data = {"things": 
           {"hello": [{"fruit": "orange"}, {"fruit": "apple"}], 
            "world": [{"fruit": "banana"}, {"fruit": "cherry"}]
           }
        }

I'd like the output to look like this:

[{"hello": ["orange", "apple"]}, {"world": ["banana", "cherry"]}]

I've tried a few things but can't quite seem to figure out the best combo. I've tried using groupby and sorted per some related examples found

d = dict([(word, list(fruits)) for word, fruits in groupby(sorted(data['things'], key=lambda x: data['things'][x]['fruit']), key=lambda x: data['things'][x])])

Like I said this is just for fun and to figure out how to combine things. I realize that it is not efficient or the most pythonic way to go about this.

1 Answers

Here's one solution, just a straight comprehension.

>>> [{k: [d["fruit"] for d in v]} for k, v in data["things"].items()]
[{'hello': ['orange', 'apple']}, {'world': ['banana', 'cherry']}]
Related