我正在尝试创建一个每个键具有多个值的字典。例如:
top_10 = ['Volkswagen_Golf_1.4', 'BMW_316i', 'Ford_Fiesta', 'BMW_318i', 'Volkswagen_Polo', 'BMW_320i', 'Opel_Corsa', 'Renault_Twingo', 'Volkswagen_Golf', 'Opel_Corsa_1.2_16V']
common_brands = ['volkswagen', 'bmw', 'opel', 'mercedes_benz', 'audi', 'ford']
我想创建一个看起来像这样的字典:
{'volkswagen': ['Volkswagen_Golf_1.4', 'Volkswagen_Polo', 'Volkswagen_Golf'], 'bmw': ['BMW_316i', 'BMW_318i', 'BMW_320i'], 'opel': ['Opel_Corsa', 'Opel_Corsa_1.2_16V'],'ford': ['Ford_Fiesta'], 'Renault': ['Reanault_Twingo']}
使用我尝试过的代码,每个品牌只能获得一个型号,并且找不到添加不在 common_brands 列表中的品牌的方法。
models_by_brand = {}
for brand in common_brands:
for model in top_10:
if brand in model.lower():
models_by_brand[brand] = [model]
models_by_brand
输出:
{'bmw': ['BMW_320i'],
'ford': ['Ford_Fiesta'],
'opel': ['Opel_Corsa_1.2_16V'],
'volkswagen': ['Volkswagen_Golf']}
慕侠2389804
Helenr
慕无忌1623718
相关分类