i have a dictionary with three key-value pairs and in which the values are a list. I want to create a list of the dictionary where the keys are string and values of that dictionary should be the value of list from each dictionary values,
I thought of iterating over that dictionary and do list comprehension where each element is a dictionary but I can't get the value for that key.
cars = {
'cars' : ['audi', 'bmw', 'xyz'],
'model' : ['abc', 'qwer', 'rty']
}
car_list = [{'car': value_audi, 'car-model': value_abc} for car in cars]
how can I get this value_audi and value_abc for each list item?
the result should be like this
car_list = [{'cars': audi, 'car_model': abc}, {'cars': bmw, 'car_model': qwer}, {'cars': xyz, 'car_model': rty}]
Use zip()
Ex.
cars = {
'cars' : ['audi', 'bmw', 'xyz'],
'model' : ['abc', 'qwer', 'rty']
}
result = [{'cars':c,'car_model':m} for c,m in zip(cars['cars'],cars['model']) ]
print(result)
O/P:
[{'cars': 'audi', 'car_model': 'abc'}, {'cars': 'bmw', 'car_model': 'qwer'}, {'cars': 'xyz', 'car_model': 'rty'}]
Use zip(*)
:
car_list = [{'car': x, 'car_model': y} for x, y in zip(*cars.values())]
Example :
cars = {
'cars' : ['audi', 'bmw', 'xyz'],
'model' : ['abc', 'qwer', 'rty']
}
car_list = [{'car': x, 'car_model': y} for x, y in zip(*cars.values())]
# [{'car': 'audi', 'car_model': 'abc'}, {'car': 'bmw', 'car_model': 'qwer'}, {'car': 'xyz', 'car_model': 'rty'}]
if you do not want to "hardcode" the keys of your new dicts you can use:
from itertools import cycle
cars = {
'cars' : ['audi', 'bmw', 'xyz'],
'model' : ['abc', 'qwer', 'rty']
}
[dict(e) for e in zip(*[zip(cycle([k]), v) for k, v in cars.items()])]
output:
[{'cars': 'audi', 'model': 'abc'},
{'cars': 'bmw', 'model': 'qwer'},
{'cars': 'xyz', 'model': 'rty'}]
Zip() can help you here.
The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
cars = {
'cars' : ['audi', 'bmw', 'xyz'],
'model' : ['abc', 'qwer', 'rty']
}
result = [{'cars':x,'car_model':y} for x,y in zip(cars['cars'],cars['model']) ]
print(result)
Expected output will be :
[{'cars': 'audi', 'car_model': 'abc'}, {'cars': 'bmw', 'car_model': 'qwer'}, {'cars': 'xyz', 'car_model': 'rty'}]
follow this link for further clarification zip()
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.