【问题标题】:Python dictionary parent child organizationPython字典父子组织
【发布时间】:2021-03-25 03:19:33
【问题描述】:

我有一个这样的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 = []

谁能提出一个有效的方法来实现这一点?

【问题讨论】:

  • 您是否保证在输入中显示的列表中排序,这意味着manufacturer_ids 至少分组为显示?
  • 高效是什么意思?您尝试过的方法失败的原因是什么?
  • 是的。要么您将遍历并创建您的对象(使用字典以提高制造商 ID 的效率。)或者您将编写一个 groupby 函数或使用内置库。这个链接很有用stackoverflow.com/questions/3749512/python-group-by
  • @TomMyddeltyn 不,输入中没有排序。这将是随机的
  • 前面有 0model_numbers 会导致错误 SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers ?我可以删除0s

标签: python python-3.x list dictionary data-structures


【解决方案1】:
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'}]}]

【讨论】:

    【解决方案2】:
    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 的子列表,并将 ``````manufacturer_id 和manufacturer_namethat matched up usingmanufacturer_id 列表中的字典作为匹配它们的键

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

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多