【问题标题】:What is the most efficient way to create nested dictionaries in Python?在 Python 中创建嵌套字典的最有效方法是什么?
【发布时间】:2020-09-10 12:35:43
【问题描述】:

我的字典中目前有超过 10k 的元素,如下所示:

cars = [{'model': 'Ford', 'year': 2010},
        {'model': 'BMW', 'year': 2019},
        ...]

我还有第二本词典:

car_owners = [{'model': 'BMW', 'name': 'Sam', 'age': 34},
              {'model': 'BMW', 'name': 'Taylor', 'age': 34},
              .....]

但是,我想将两者结合在一起,就像:

combined = [{'model': 'BMW',
             'year': 2019,
             'owners: [{'name': 'Sam', 'age': 34}, ...]
            }]

将它们结合起来的最佳方法是什么?目前我正在使用 For 循环,但我觉得有更有效的方法来处理这个问题。

** 这只是一个虚假的数据示例,我拥有的数据要复杂得多,但这有助于了解我想要实现的目标

【问题讨论】:

  • 我认为问题是双重的。 stackoverflow.com/questions/53601657/…
  • 这些不是字典,而是(字典的)列表。如果至少有一个是真正的 dict,那么合并会更快,因为您不必“搜索”匹配模型。
  • 福特去哪儿了?
  • 对于这么多的数据,您需要开始考虑使用 SQLite(或其他数据库)之类的东西。您不会有许多dict 对象的内存开销,并且可以使用SQL 生成所需的组合。

标签: python dictionary


【解决方案1】:

遍历第一个列表,创建一个以 key-val 为 model-val 的字典,然后在第二个字典中查找相同的键(模型)并更新第一个字典(如果找到):

cars = [{'model': 'Ford', 'year': 2010}, {'model': 'BMW', 'year': 2019}]
car_owners = [{'model': 'BMW', 'name': 'Sam', 'age': 34}, {'model': 'Ford', 'name': 'Taylor', 'age': 34}]


dd = {x['model']:x for x in cars}

for item in car_owners:
    key = item['model']
    if key in dd:
        del item['model']
        dd[key].update({'car_owners': item})
    else:
        dd[key] = item

print(list(dd.values()))

输出:

[{'model': 'BMW', 'year': 2019, 'car_owners': {'name': 'Sam', 'age': 34}}, {'model': 'Ford', 'year': 2010, 'car_owners': {'name': 'Taylor', 
'age': 34}}] 

【讨论】:

    【解决方案2】:

    真的,你想要的性能明智的是将模型作为关键的字典。这样,您有 O(1) 查找并且可以快速获取请求的元素(而不是每次循环以查找型号为 x 的汽车)。 如果您从列表开始,我会先创建字典,然后从那里开始一切都是 O(1)。

    models_to_cars = {car['model']: car for car in cars}
    models_to_owners = {}
    for car_owner in car_owners:
        models_to_owners.setdefault(car_owner['model'], []).append(car_owner)
    
    
    combined = [{
        **car,
        'owners': models_to_owners.get(model, [])
    } for model, car in models_to_cars.items()]
    

    那么你就有了

    combined = [{'model': 'BMW',
                 'year': 2019,
                 'owners': [{'name': 'Sam', 'age': 34}, ...]
                }]
    

    如你所愿

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多