简体   繁体   English

以列表理解为值的字典理解

[英]Dictionary comprehension with list comprehension as values

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.我相当肯定这个问题的解决方案根本不是pythonic,但我很想知道人们实际上会如何去做go。 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:我希望 output 看起来像这样:

[{"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我尝试使用groupby并根据找到的一些相关示例sorted

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.我意识到 go 这不是有效的或最pythonic的方式。

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']}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM