简体   繁体   English

从列表创建基于SEQUENCE的字典

[英]Create SEQUENCE based dictionary from list

I have a list of dictionaries like this, 我有这样的字典清单,

I am trying to prepare a dictionary from the list , 我正在尝试从清单中准备字典,

the list is like this, 清单是这样的

result = [{'comp_seq': 1, 'benefit_category_name': 'Standard Benefits', 
           'sale_line_id': 34353, 'benefit_name': 'TPA',  
           'insurance_category_name': 'A', 'benefit_categ_seq': 1},
          {'comp_seq': 1, 'benefit_category_name': 'Standard Benefits', 
           'sale_line_id': 34354,'benefit_name': 'TPA', 
           'insurance_category_name': 'B', 'benefit_categ_seq': 1},
          {'comp_seq': 1, 'benefit_category_name': 'Standard Benefits', 
           'sale_line_id': 34355, 'benefit_name': 'TPA',  
           'insurance_category_name': 'A', 'benefit_categ_seq': 1}, 
          {'comp_seq': 1,  'benefit_category_name': 'Standard Benefits',  
           'sale_line_id': 34356, 'insurance_category_name': 'B', 
           'benefit_categ_seq': 1}]

I looking for the dictionary like this, 我在寻找这样的字典,

{1: 
    {'Standard Benefits': 
        {1: 
            {'TPA': 
                [{'B': 
                    [{34353: [None, True, None, False]},
                     {34354: ['Aafiya', False, None, False]}, 
                     {34355: [None, True, None, False]}, 
                     {34356: ['Aafiya', False, None, False]}]}, 

                 {'A': 
                    [{34353: [None, True, None, False]},
                     {34354: ['Aafiya', False, None, False]}, 
                     {34355: [None, True, None, False]}, 
                     {34356: ['Aafiya', False, None, False]}]},
                    ]
                 }
            }
        }
    }

But actually I get the dictionary like this after my code, 但是实际上我在代码之后得到了这样的字典,

{1: 
    {'Standard Benefits': 
        {1: 
            {'TPA': 
                [{'B': 
                    [{34353: [None, True, None, False]},
                     {34354: ['Aafiya', False, None, False]}, 
                     {34355: [None, True, None, False]}, 
                     {34356: ['Aafiya', False, None, False]}]}, 
                 {'A': [}]},
                ]
            }
        }
    }
}

Here is the code I wrote to prepare the dictionary, 这是我准备字典的代码,

cat1= []
for key, value in itertools.groupby(result, key=itemgetter('insurance_category_name')):
    cat1.append(key)
cat = list(set(cat1))
seq_d = {}
seq_sort_res = sorted(result, key=itemgetter('benefit_categ_seq'))
for seq, bc_val in itertools.groupby(seq_sort_res, key=itemgetter('benefit_categ_seq')):
    bc_d = {}
    ben_categ_sort_result = sorted(bc_val, key=itemgetter('benefit_category_name'))
    for bc, bf_val in itertools.groupby(ben_categ_sort_result, key=itemgetter('benefit_category_name')):
        bseq_d = {} 
        benefit_seq = sorted(bf_val, key=itemgetter('comp_seq'))
        for bseq, bseq_val in itertools.groupby(benefit_seq, key=itemgetter('comp_seq')):
            bf_d = {} 
            for bf in bseq_val:
                if bf.get('benefit_name') not in bf_d:
                    bf_d.update({bf.get('benefit_name'): []})
                    for c in cat:
                        if c not in bf_d[bf.get('benefit_name')]:
                           bf_d.get(bf.get('benefit_name')).append({c: []})
                content = []
                vals = ['description', 'is_checked', 'comment', 'highlight']
                for v in vals:
                    content.append(bf.get(v))
                s = {bf.get('sale_line_id'): content} 
                list(bf_d[bf.get('benefit_name')][0].values())[0].append(s)
            bseq_d.update({bseq: bf_d})
        bc_d.update({bc: bseq_d})
    seq_d.update({seq: bc_d})

But the dictionary is not correctly prepared. 但是字典准备不正确。 I think some problem in looping.please identify the problem in my code? 我认为循环中存在一些问题。请在代码中找出问题所在?

update 更新


The logic behind this problem is I decided to create dictionary like firstly benefit category sequence then next to benefit category then next one is benefit sequence and benefit like this. 这个问题背后的逻辑是,我决定首先像这样创建字典,即利益类别序列,然后是利益类别,然后下一个是利益序列和利益。

With in the benefit i added a list for category 'A' and 'B' .within the list there is a dictionary for 'A' and 'B' , key is sale_line_id and values are from sale_line_id, here is 4 sale_line id s. 在好处中,我添加了类别“ A”和“ B”的列表。在该列表中,有一个字典“ A”和“ B” ,键是sale_line_id,值来自sale_line_id, 这里是4 sale_line id and corresponding values. 和相应的值。

The inner dictionary for category 'B' is formed correctly, but the problem is the inner dictionary if 'A' for wrong 类别“ B”的内部字典格式正确,但是问题在于如果“ A”表示错误内部字典

update2 UPDATE2


the bf dictionary from for bf in bseq_val: bseq_val中来自bf的bf字典:

the bf dictionary is bf字典是

 {'is_checked': False, 'highlight': False, 'comment': None, 
  'comp_seq': 1, 'description': 'Aafiya', 'benefit_name': 'TPA', 
  'insurance_category_name': 'B', 'benefit_categ_seq': 1,  
  'benefit_category_name': 'Standard Benefits', 'sale_line_id': 34354}

this type of 4 dictionaries formed in looping. 这种4个字典在循环中形成。 the only major different is the category 'A' for 2 dictionaries and 'B' for 2 dictionaries. 唯一的不同是2个字典类别“ A”和2个字典类别“ B”

What you are trying to achieve is not clear to me. 您想达到的目标对我来说还不清楚。 But, if I understand, you want to transform a list of dicts into a tree (or a forest if you have more than one root), following a predefined list of groups. 但是,据我了解,您希望按照预定义的组列表将字典列表转换为树(如果您有多个根,则为森林)。 The groups are ordered from the roots to the leaves: 这些组从根到叶是有序的:

groups = ['benefit_categ_seq', 'benefit_category_name', 'comp_seq', 'insurance_category_name', 'sale_line_id']

Instead of hardcoding the hierarchy, you can use the list above to build the tree: 您可以使用上面的列表来构建树,而不是对层次结构进行硬编码:

def nest(L, path):
    *init_path, last_path = path # split before the last element
    root = {}
    for d in L:
        e = root # start at the root
        for g in init_path: # follow the path
            e = e.setdefault(d[g], {}) # get or create the subtree
        e[d[last_path]] = d # add the dict to the leaf

    return root

For every dict (that is the representation of a business object), start from the root, and follow the path: 对于每个字典(即业务对象的表示形式),从根开始,并遵循以下路径:

  • before the last element of the path, get or create ( setdefault ) the subtrees; 在路径的最后一个元素之前,获取或创建( setdefault )子树;
  • when you reach the last element of the path, that is the id of your object, attach the object. 当您到达路径的最后一个元素(即对象的ID)时,请附加该对象。

Here's the result: 结果如下:

from pprint import pprint
pprint (nest(result, groups))
{1: {'Standard Benefits': {1: {'A': {34353: {'benefit_categ_seq': 1,
                                             'benefit_category_name': 'Standard '
                                                                      'Benefits',
                                             'benefit_name': 'TPA',
                                             'comp_seq': 1,
                                             'insurance_category_name': 'A',
                                             'sale_line_id': 34353},
                                     34355: {'benefit_categ_seq': 1,
                                             'benefit_category_name': 'Standard '
                                                                      'Benefits',
                                             'benefit_name': 'TPA',
                                             'comp_seq': 1,
                                             'insurance_category_name': 'A',
                                             'sale_line_id': 34355}},
                               'B': {34354: {'benefit_categ_seq': 1,
                                             'benefit_category_name': 'Standard '
                                                                      'Benefits',
                                             'benefit_name': 'TPA',
                                             'comp_seq': 1,
                                             'insurance_category_name': 'B',
                                             'sale_line_id': 34354},
                                     34356: {'benefit_categ_seq': 1,
                                             'benefit_category_name': 'Standard '
                                                                      'Benefits',
                                             'comp_seq': 1,
                                             'insurance_category_name': 'B',
                                             'sale_line_id': 34356}}}}}}

I know that's not the exact output you need, but might help. 我知道这不是您需要的确切输出,但可能会有所帮助。

If the last_path is an not an unique id, get or create the leaf (a list) and append the current dict: e.setdefault(d[last_path], []).append(d) instead of e[d[last_path]] = d . 如果last_path不是唯一ID,则获取或创建叶子(列表)并附加当前字典: e.setdefault(d[last_path], []).append(d)代替e[d[last_path]] = d ` `

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

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