简体   繁体   English

在 Python 中创建嵌套字典的最有效方法是什么?

[英]What is the most efficient way to create nested dictionaries in Python?

I currently have over 10k elements in my dictionary looks like:我的字典中目前有超过 10k 个元素,如下所示:

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

And I have a second dictionary:我还有第二本字典:

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

However, I want to join together the 2 together to be something like:但是,我想将这两个结合在一起成为类似的东西:

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

What is the best way to combine them?将它们结合起来的最佳方法是什么? For the moment I am using a For loop but I feel like there are more efficient ways of dealing with this.目前我正在使用 For 循环,但我觉得有更有效的方法来处理这个问题。

** This is just a fake example of data, the one I have is a lot more complex but this helps give the idea of what I want to achieve **这只是一个虚假的数据示例,我拥有的数据要复杂得多,但这有助于了解我想要实现的目标

Iterate over the first list, creating a dict with the key-val as model-val, then in the second dict, look for the same key (model) and update the first dict, if it is found:迭代第一个列表,创建一个键值作为模型值的字典,然后在第二个字典中查找相同的键(模型)并更新第一个字典(如果找到):

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()))

OUTPUT:输出:

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

Really, what you want performance wise is to have dictionaries with the model as the key.真的,你想要的性能明智是以模型为关键的字典。 That way, you have O(1) lookup and can quickly get the requested element (instead of looping each time in order to find the car with model x).这样,您就可以进行 O(1) 查找并且可以快速获取请求的元素(而不是每次都循环以查找模型为 x 的汽车)。 If you're starting off with lists, I'd first create dictionaries, and then everything is O(1) from there on out.如果您从列表开始,我会首先创建字典,然后从那里开始一切都是 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()]

Then you'd have那么你会有

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

as you wanted如你所愿

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

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