gpt4 book ai didi

python - 按对象属性对对象字典进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:23 25 4
gpt4 key购买 nike

我有一个类 Metric 对象的字典。每个 Metric 对象都有一个名为 category 的属性(例如,“cat1”、“cat2”……)。按 category 排列 dict 的最聪明的方法是什么?

我现在的解决方案是通过迭代每个对象来创建一组所有类别,然后再次迭代并将每个对象分配给一个类别,但我认为可能有更有效的方法吗?

我有什么:

{'a': <__main__.Metric at 0xb1e3470>,
'b': <__main__.Metric at 0xb14f7b8>,
'c': <__main__.Metric at 0xb160828>,
'd': <__main__.Metric at 0x5ee9128>,
'e': <__main__.Metric at 0xb14f550>,
'f': <__main__.Metric at 0xb14ff98>,
'g': <__main__.Metric at 0xb14fa58>,
...}

我想要什么:

{'cat1': [<__main__.Metric at 0xb160828>, ...]
'cat2': [<__main__.Metric at 0xb14f550>, ...],
...}

最佳答案

你应该使用 collections.defaultdict喜欢:

from collections import defaultdict

my_dict = defaultdict(list)

for obj in your_dict.values():
my_dict[obj.category].append(obj)
# ^ object category as key

your_dict 是保存问题中提到的当前字典的结构

关于python - 按对象属性对对象字典进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com