分组中的默认字典

时间:2019-05-07 14:20:22

标签: python defaultdict

我的代码给我的结果与断言功能不起作用的结果相同。 可能是什么问题?

我尝试将“ return d”功能右移一个选项卡以缩短代码可能执行的操作,并且在打印“ groups1”和“ test_max_item”之后,输出结果相似。但是assert函数仍然失败。


Scripts =[ { ‘a’: ‘1, ‘bnf_name’: ‘joy’, ‘items’ : 3}
{ ‘a’ :2, ‘ bnf_name’: ‘loss’, ‘ items’: 6}....]
from collections import defaultdict

def group_by_field(dictionary, grpbykey): 
    d = defaultdict(list)
    for poop in dictionary: 
        d[poop[grpbykey]].append(poop)
    return d

groups1 = group_by_field(scripts, 'bnf_name')
test_max_item = group_by_field(scripts,'bnf_name')
assert test_max_item == groups1

我希望没有断言错误。

1 个答案:

答案 0 :(得分:0)

您的代码缺乏可读性(x100)。无论如何,也许这就是您想要的:

from collections import defaultdict


scripts = [{'a': 1, 'bnf_name': 'joy', 'items': 3}, {'a': 2, ' bnf_name': 'loss', ' items': 6}]
reverse_scripts = [{val:key for val,key in d.iteritems()} for d in scripts]


def group_by_field(dictionaries, grpbykey):
    d = defaultdict(list)
    for dictionary in dictionaries:
        if grpbykey in dictionary:
            d[grpbykey].append(dictionary[grpbykey])
    return d


groups1 = group_by_field(reverse_scripts, 'bnf_name')
test_max_item = group_by_field(reverse_scripts, 'bnf_name')
assert test_max_item == groups1