Python字典父子组织

2024-06-17 18:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的list

laptop_list = [
{"manufacturer_id": 1 , "manufacturer_name": "Lenovo", "model_number": 000000, "model_name": "Legion"}, 
{"manufacturer_id": 1 , "manufacturer_name": "Lenovo", "model_number": 999999, "model_name": "Ideapad"}, 
{"manufacturer_id": 2 , "manufacturer_name": "HP", "model_number": 0101010, "model_name": "pavillion"} ,
{"manufacturer_id": 2 , "manufacturer_name": "HP", "model_number": 0202020, "model_name": "Inspiron"} ]

我需要重新构造上面的列表,类似于

[{"manufacturer_id": 1 , "manufacturer_name": "Lenovo", "models":[{"model_number": 000000, "model_name": "Legion"}, {"model_number": 999999, "model_name": "Ideapad"}]},
{"manufacturer_id": 2 , "manufacturer_name": "HP", "models":[{"model_number": 0101010, "model_name": "pavillion"} , {"model_number": 0202020, "model_name": "Inspiron"}]} ]

我尝试使用node类,但未能达到预期的结果

class LaptopNode:

    def __init__(self, manufacturer_id, manufacturer_name):
        self.manufacturer_id = manufacturer_id
        self.manufacturer_name = manufacturer_name
        self.child_models = []

有人能提出一个有效的方法来实现这一点吗


Tags: nameselfidnumbermodelmodelslisthp
3条回答
from more_itertools import bucket
from operator import itemgetter
from pprint import pprint

laptop_list = [
{"manufacturer_id": 1 , "manufacturer_name": "Lenovo", "model_number": '000000', "model_name": "Legion"},
{"manufacturer_id": 2 , "manufacturer_name": "HP", "model_number": '0101010', "model_name": "pavillion"},
{"manufacturer_id": 1 , "manufacturer_name": "Lenovo", "model_number": '999999', "model_name": "Ideapad"},
{"manufacturer_id": 2 , "manufacturer_name": "HP", "model_number": '0202020', "model_name": "Inspiron"},
{"manufacturer_id": 1 , "manufacturer_name": "Lenovo", "model_number": '999999', "model_name": "Ideapad"},
{"manufacturer_id": 2 , "manufacturer_name": "HP", "model_number": '0202020', "model_name": "Inspiron"} ]

m_id = itemgetter('manufacturer_id')
bucketed = bucket(laptop_list, m_id)
result = []

for i in bucketed:
    d = {'model': []}

    for j in bucketed[i]:
        _d = j
        
        for k, v in sorted(j.items())[:2]:
            d[k] = v
            _d.pop(k)
        else:
            d['model'].append(_d)

    result.append(dict(sorted(d.items())))

pprint(result)
[{'manufacturer_id': 1,
  'manufacturer_name': 'Lenovo',
  'model': [{'model_name': 'Legion', 'model_number': '000000'},
            {'model_name': 'Ideapad', 'model_number': '999999'},
            {'model_name': 'Ideapad', 'model_number': '999999'}]},
 {'manufacturer_id': 2,
  'manufacturer_name': 'HP',
  'model': [{'model_name': 'pavillion', 'model_number': '0101010'},
            {'model_name': 'Inspiron', 'model_number': '0202020'},
            {'model_name': 'Inspiron', 'model_number': '0202020'}]}]

谢谢你的回复。我也在发布我的方法

class LaptopNode:

    def __init__(self, manufacturer_id):
        self.manufacturer_name = None
        self.manufacturer_id = manufacturer_id
        self.child_models = []

    def add_child_device(self, child_model):
        self.child_models.append(child_model)


if __name__ == "__main__":
    modified_list = []

    # Remove duplicate parents
    parent_laptop_set = {laptop['manufacturer_id'] for laptop in laptop_list}

    # Create a instance for each parent
    laptop_instance_dictt = {manufacturer_id: LaptopNode(manufacturer_id) for manufacturer_id in parent_laptop_set}

    # Iterate through original list and map child models to parent
    for laptop in laptop_list:
        model = laptop_instance_dictt[laptop['manufacturer_id']]
        model.manufacturer_name = laptop['manufacturer_name']
        model.add_child_device({'model_name': laptop['model_name'], 'model_number': laptop['model_number']})

    for laptop_instance in laptop_instance_dictt.values():
        modified_list.append(
            {"manufacturer_id": laptop_instance.manufacturer_id, "manufacturer_name": laptop_instance.manufacturer_name,
             "models": laptop_instance.child_models})
    print(modified_list)
dictt = list(map(lambda x: {'manufacturer_id':x['manufacturer_id'],'manufacturer_name':x['manufacturer_name'] }, laptop_list))
no_duplicate_dict = [dict(t) for t in {tuple(d.items()) for d in dictt}]

sub_dict = list(map(lambda x: [x['manufacturer_id'], {'model_number':x['model_number'], 'model_name':x['model_name']}], laptop_list))

grouped_dict = [    [ID]+[[x[1] for x in sub_dict if x[0] == ID]] for ID in set([id[0] for id in sub_dict])   ]

list(map(lambda x: x.update( {'models' : [sub_dict[1][0-len(sub_dict[1])] for sub_dict in grouped_dict if x['manufacturer_id'] == sub_dict[0]] }), no_duplicate_dict))

print(no_duplicate_dict)

>>> [{'manufacturer_id': 2, 'manufacturer_name': 'HP', 'models': [{'model_number': 101010, 'model_name': 'pavillion'}]}, {'manufacturer_id': 1, 'manufacturer_name': 'Lenovo', 'models': [{'model_number': 0, 'model_name': 'Legion'}]}]

我把一个用manufacturer_id and manufacturer_name和另一个用model_number and model_name分开列出

然后,我添加了来自model_number and model_name的子列表,其中的字典位于``制造商id和制造商名称that matched up using制造商id``列表中,作为匹配它们的键

这一行no_duplicate_dict = [dict(t) for t in {tuple(d.items()) for d in dictt}]刚刚删除了重复的字典

相关问题 更多 >