Skip to content Skip to sidebar Skip to footer

Data Structure In Python

names=['Peter', 'John'] size = ['X', 'M', 'L'] list_price = [1, 2, 3, 4, 5, 6] # There are 2 people will buy 3 size of shirt I want to create my data structure into: [ {'name':

Solution 1:

You can turn list_price into an iterator and then use next to get one value after the other:

>>> iterator = iter(list_price)
>>> [{"name": n, "size_price": {s: next(iterator) for s in size}} for n in names]
[{'size_price': {'X': 1, 'M': 2, 'L': 3}, 'name': 'Peter'}, 
 {'size_price': {'X': 4, 'M': 5, 'L': 6}, 'name': 'John'}]

Of course you do not have to use a list comprehension but can do the same thing with nested loops as well.

Post a Comment for "Data Structure In Python"