Let's say I have users (John, Anna) that can order fruits (oranges, apples) in a quantity of their choice.
Here is what I have done in python :
orders = (('John', (('apples', 3), ('oranges', 1))),
('Anna', (('oranges', 6))))
I'd like to iterate over the orders :
for user, order in orders:
for fruit, quantity in order:
print "%s wants %d %s" % (user, quantity, fruit)
This is the output i'm expecting :
John wants 3 apples
John wants 1 oranges
Anna wants 6 oranges
I get a ValueError: too many values to unpack. What am I doing wrong?
Should I use something else than tuples? Is it my iteration that is bad?
It would have been useful to show the exact traceback.
The error is simply that Anna's order isn't actually a nested tuple: it's a simple tuple. You are missing a comma at the end:
orders = (('John', (('apples', 3), ('oranges', 1))),
('Anna', (('oranges', 6),)))
# ^ here
Remember it's the comma that makes the tuple, not the parentheses.
As others have stated though, nested dicts would be more appropriate here.
Daniel has given an excellent answer to:
What am I doing wrong?
But to address your second question:
Should I use something else than tuples?
I would say that this is a much better fit for a dictionary:
>>> orders = {'John': {'apples': 3, 'oranges': 1}, 'Anna': {'oranges': 6}}
>>> for user, order in orders.items():
for fruit, quantity in order.items():
print "{0} wants {1} {2}".format(user, quantity, fruit)
Anna wants 6 oranges
John wants 1 oranges
John wants 3 apples
(Note that dictionaries are not guaranteed to retain the order of their contents - if the order is crucial, there is an alternative collections.OrderedDict that guarantees retention of insertion order.)
This is particularly useful to answer questions like "how many apples did John want?"
>>> orders['John']['apples']
3
which can be altered to guard against someone not having ordered that fruit, for example if you want to find out "how many apples were ordered in total?"
>>> sum(order.get('apples', 0) for order in orders.values())
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With