Gillytron
Gillytron

Reputation: 21

How to extract the nth element of a nested list, where each inner list contains x elements and returned as a dictionary?

I have the following nested list:

orders = [['Large', 'Latte', 2.45],
['',
'Frappes - Coffee',
2.75,
'',
'Cortado',
2.05,
'',
'Glass of milk',
0.7,
'',
'Speciality Tea - Camomile',
1.3,
'',
'Speciality Tea - Camomile',
1.3]]

Each inner list is n elements long, but always divisible by 3.

My issue is that I am trying to return a list of dictionaries by iterating through orders with the following:

[dict(size=i[0],product=i[1],price=i[2]) for i in orders]

However, that only returns the first element inside products[1]

returns [{'size': 'Large', 'product': 'Latte', 'price': 2.45},
 {'size': '', 'product': 'Frappes - Coffee', 'price': 2.75}]

I tried doing a second loop but that also doesn't work.

I want my code to output the following:

[
[{'size': 'Large', 'product': 'Latte', 'price': 2.45}],
[{'size': '', 'product': 'Frappes - Coffee', 'price': 2.75}, 
{'size': '', 'product': 'Cortado', 'price': 2.05}, 
{'size': '', 'product': 'Glass of Milk', 'price': 0.7}, 
{'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3}, 
{'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3}]
]

If anyone could point me in the right direction it would be much appreciated!

Upvotes: 0

Views: 358

Answers (2)

Chris
Chris

Reputation: 29752

You can iterate the sublists as chunk of size 3 and then make dict:

def chunks(lst, n):
    """Yield successive n-sized chunks from lst.
    https://stackoverflow.com/questions/312443/how-do-you-split-a- 
    list-into-evenly-sized-chunks
    """
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

[[dict(size=i[0],product=i[1],price=i[2]) 
  for i in chunks(order, 3)] 
  for order in orders]

Output:

[[{'size': 'Large', 'product': 'Latte', 'price': 2.45}],
 [{'size': '', 'product': 'Frappes - Coffee', 'price': 2.75},
  {'size': '', 'product': 'Cortado', 'price': 2.05},
  {'size': '', 'product': 'Glass of milk', 'price': 0.7},
  {'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3},
  {'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3}]]

Upvotes: 3

Brandon Kauffman
Brandon Kauffman

Reputation: 1864

The problem is orders is inconsistent. Fix it by changing it to make each new order a list would be the best solution

orders = [
    ["Large", "Latte", 2.45],
    ["", "Frappes - Coffee", 2.75],
    ["", "Cortado", 2.05],
    ["", "Glass of milk", 0.7],
    ["","Speciality Tea - Camomile",1.3],
    ["","Speciality Tea - Camomile",1.3]
]

Upvotes: -1

Related Questions