繁体   English   中英

如何有效地根据python中键的值对字典列表进行分类?

[英]How to categorize list of dictionaries based on the value of a key in python efficiently?

我在python中有一个字典列表,我想根据所有字典中存在的键的值对它们进行分类,并分别处理每个类别。 我不知道有什么价值,我只知道存在一个特殊的关键。 这是清单:

dictList = [
            {'name': 'name1', 'type': 'type1', 'id': '14464'}, 
            {'name': 'name2', 'type': 'type1', 'id': '26464'},
            {'name': 'name3', 'type': 'type3', 'id': '36464'},
            {'name': 'name4', 'type': 'type5', 'id': '43464'},
            {'name': 'name5', 'type': 'type2', 'id': '68885'}
            ]

这是我目前使用的代码:

while len(dictList):
    category = [l for l in dictList if l['type'] == dictList[0]['type']]
    processingMethod(category)
    for item in category:
        dictList.remove(item)

上面列表中的这个迭代将给出以下结果:

Iteration 1:
            category = [
                        {'name': 'name1', 'type': 'type1', 'id': '14464'}, 
                        {'name': 'name2', 'type': 'type1', 'id': '26464'},
                        ]

Iteration 2:
            category = [
                        {'name': 'name3', 'type': 'type3', 'id': '36464'}
                        ]

Iteration 3:
            category = [
                        {'name': 'name4', 'type': 'type5', 'id': '43464'}
                        ]

Iteration 4:
            category = [
                        {'name': 'name5', 'type': 'type2', 'id': '68885'}
                        ]

每次,我得到一个类别,处理它,最后删除处理的项目以迭代剩余的项目,直到没有剩余的项目。 有什么想让它变得更好吗?

您的代码可以使用itertools.groupby重写

for _, category in itertools.groupby(dictList, key=lambda item:item['type']):
    processingMethod(list(category))

或者,如果processingMethod可以处理iterable

for _, category in itertools.groupby(dictList, key=lambda item:item['type']):
    processingMethod(category)

如果l['type']对于dictList每个l都是可dictList ,这里有一个可能的,有点优雅的解决方案:

bins = {}

for l in dictList:
    if l['type'] in bins:
        bins[l['type']].append(l)
    else:
        bins[l['type']] = [l]

for category in bins.itervalues():
   processingMethod(category)

我们的想法是,首先,我们将所有l s分类为bin,使用l['type']作为键; 第二,我们将处理每个垃圾箱。

如果不确保l['type']dictList每个l都是可散列的,那么方法基本相同,但是我们必须使用元组列表而不是dict,这意味着它有点少了高效:

bins = []

for l in dictList:
    for bin in bins:
        if bin[0] == l['type']:
            bin[1].append(l)
            break
    else:
        bins.append((l['type'], [l]))

for _, category in bins:
   processingMethod(category)

暂无
暂无

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

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