Hi I have a dictionary where the values are made of multiple lists. Example:
overallorders={1: [['B1', '1'], ['B2', '2'], ['B3', '1']], 2: [['B3', '4'], ['B2', '4']]}
How do I retrieve/print only the 1st or 2nd item of each list? For example, I intend to print as per the dictionary above:
Order 1
B1 qty 1 price is $4 x 1 = $4
B2 qty 2 price is $2 x 2 = $4
B3 qty 1 price is $10 x 1 = $10
Order 2
B3 qty 4 price is $10 x 4 = $40
B2 qty 4 price is $2 x 4 = $8
Currently, my progress is as follows:
for key, value in overallorders.items():
print('order number ',key)
print(value)
The output of that is:
order number 1
[['B1', '1'], ['B2', '2'], ['B3', '1']]
order number 2
[['B3', '4'], ['B2', '4']]
As you can see from the progress, I can only manage to print a whole set of lists per key. Any advice on how to retrieve each value from each list from each key?
CodePudding user response:
You can do
for order, things in overallorders.items():
print(f'Order {order}\n')
for thing, quantity in things:
print(f'{thing} qty {quantity} price is $? x {quantity} = $?')
I don't know where the price is supposed to come from so I inserted a '?'
character.
CodePudding user response:
You can use items
with f-string:
prices = {'B1': 4, 'B2': 2, 'B3': 10}
overallorders = {1: [['B1', '1'], ['B2', '2'], ['B3', '1']], 2: [['B3', '4'], ['B2', '4']]}
for order, items in overallorders.items():
print(f"Order {order}")
for item, quantity in items:
price = prices[item]
print(f"{item} qty {quantity} price is ${price} x {quantity} = ${price * int(quantity)}")
Output:
Order 1
B1 qty 1 price is $4 x 1 = $4
B2 qty 2 price is $2 x 2 = $4
B3 qty 1 price is $10 x 1 = $10
Order 2
B3 qty 4 price is $10 x 4 = $40
B2 qty 4 price is $2 x 4 = $8
CodePudding user response:
You need to loop through the dictionary to get the list from each order. Within that loop, you loop through the list.
overallorders={1: [['B1', '1'], ['B2', '2'], ['B3', '1']], 2: [['B3', '4'], ['B2', '4']]}
for key in overallorders:
print("Order {}".format(key))
for item in overallorders[key]:
print("{} qty {}".format(item[0], item[1]))
print() # print a spacer line between orders
Results:
Order 1
B1 qty 1
B2 qty 2
B3 qty 1
Order 2
B3 qty 4
B2 qty 4
CodePudding user response:
I don't know where is the source of prices, But you can do this:
for k , v in overallorders.items():
print("\norder{}".format(k))
i = 0
for value in v:
print("{} qty {} price is $4 x 1 = $4".format(v[i][0] , v[i][1]))
i = 1
This code gives me:
order1
B1 qty 1 price is $4 x 1 = $4
B2 qty 2 price is $4 x 1 = $4
B3 qty 1 price is $4 x 1 = $4
order2
B3 qty 4 price is $4 x 1 = $4
B2 qty 4 price is $4 x 1 = $4