将词典列表转换为词典的嵌套列表(合并重复值)

时间:2020-10-30 01:33:39

标签: python list python-2.7 dictionary nested

我想用字典列表创建一个嵌套的列表字典。

示例数据:

 data = [ { 'State': 'IL', 'City': 'Chicago', 'Schools': [ 'school_a', 'school_b' ] },
          { 'State': 'IL', 'City': 'Chicago', 'Schools': [ 'school_c', 'school_d' ] },
          { 'State': 'IL', 'City': 'Evanston', 'Schools': [ 'school_x', 'school_y' ] }]

所需的输出数据:

new_data = { 'IL' : [ 'Chicago'  : { 'Schools': ['school_a', 'school_b', 'school_c', 'school_d'] },
                      'Evanston' : { 'Schools : ['school_x', 'school_y'] } ] }

最有效的方法是什么?

--->编辑如下:

@Samwise的以下解决方案适用于上述示例。

如果我们也将Schools变成一个哈希,又想在下面创建这样的东西怎么办:

我们如何去做?

#Example data:

 data = [ { 'State': 'IL', 'City': 'Chicago', 'Schools': { 'high' : 'school_a', 'midddle' : 'school_b' } },
          { 'State': 'IL', 'City': 'Chicago', 'Schools': { 'high' : 'school_c', 'middle' :'school_d' } },
          { 'State': 'IL', 'City': 'Evanston', 'Schools': { 'high' :'school_x', 'middle' : 'school_y' } }]

#Desired output data:

new_data = { 'IL' : [ 'Chicago'  : [ { 'Schools': {'high': 'school_a', 'middle': 'school_b'} },
                                    { 'Schools': {'high': 'school_c', 'middle': 'school_d'} } ],
                     'Evanston' : { 'Schools : {'high': 'school_x', 'middle': 'school_y'} } ] }

1 个答案:

答案 0 :(得分:0)

当您遍历原始defaultdict时,我会使用data轻松地向字典中添加元素:

>>> new_data = defaultdict(lambda: defaultdict(lambda: {'Schools': []}))
>>> for row in data:
...     new_data[row['State']][row['City']]['Schools'].extend(row['Schools'])