简体   繁体   中英

Cartesian product giving a dictionary

I have the following lists:

brand=["Audi","Mercedes"]
speed=[130,150]
model=["sport","family"]

I want to obtain the equivalent of:

ll=[]
ll.append({'brand':'mercedes', 'speed':130, 'model':'family'})
ll.append({'brand':'mercedes', 'speed':130, 'model':'sport'})
ll.append({'brand':'audi', 'speed':130, 'model':'family'})
ll.append({'brand':'audi', 'speed':130, 'model':'sport'})
ll.append({'brand':'mercedes', 'speed':150, 'model':'family'})
ll.append({'brand':'mercedes', 'speed':150, 'model':'sport'})
ll.append({'brand':'audi', 'speed':150, 'model':'family'})
ll.append({'brand':'audi', 'speed':150, 'model':'sport'})

I currently do:

from itertools import product
ll=list(product(speed, model, brand))

I have all needed combinations but this is simply a list of list and not a list of dictionary. I don't know if there is a direct and pythonic way to do it!

Zip your values with the keys:

keys = 'brand', 'speed', 'model'

ll = [dict(zip(keys, combo)) for combo in product(brand, speed, model)]

Demo:

>>> from itertools import product
>>> from pprint import pprint
>>> brand = ["Audi", "Mercedes"]
>>> speed = [130, 150]
>>> model = ["sport", "family"]
>>> keys = 'brand', 'speed', 'model'
>>> [dict(zip(keys, combo)) for combo in product(brand, speed, model)]
[{'speed': 130, 'brand': 'Audi', 'model': 'sport'}, {'speed': 130, 'brand': 'Audi', 'model': 'family'}, {'speed': 150, 'brand': 'Audi', 'model': 'sport'}, {'speed': 150, 'brand': 'Audi', 'model': 'family'}, {'speed': 130, 'brand': 'Mercedes', 'model': 'sport'}, {'speed': 130, 'brand': 'Mercedes', 'model': 'family'}, {'speed': 150, 'brand': 'Mercedes', 'model': 'sport'}, {'speed': 150, 'brand': 'Mercedes', 'model': 'family'}]
>>> pprint(_)
[{'brand': 'Audi', 'model': 'sport', 'speed': 130},
 {'brand': 'Audi', 'model': 'family', 'speed': 130},
 {'brand': 'Audi', 'model': 'sport', 'speed': 150},
 {'brand': 'Audi', 'model': 'family', 'speed': 150},
 {'brand': 'Mercedes', 'model': 'sport', 'speed': 130},
 {'brand': 'Mercedes', 'model': 'family', 'speed': 130},
 {'brand': 'Mercedes', 'model': 'sport', 'speed': 150},
 {'brand': 'Mercedes', 'model': 'family', 'speed': 150}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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