python - Cartesian product giving a dictionary -
i have following lists:
brand=["audi","mercedes"] speed=[130,150] model=["sport","family"]
i want obtain 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 do:
from itertools import product ll=list(product(speed, model, brand))
i have needed combinations list of list , not list of dictionary. don't know if there direct , pythonic way it!
zip values keys:
keys = 'brand', 'speed', 'model' ll = [dict(zip(keys, combo)) combo in product(brand, speed, model)]
demo:
>>> itertools import product >>> pprint import pprint >>> brand = ["audi", "mercedes"] >>> speed = [130, 150] >>> model = ["sport", "family"] >>> keys = 'brand', 'speed', 'model' >>> [dict(zip(keys, combo)) 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}]
Comments
Post a Comment