-1
def get_quantities(table_to_foods):
    """ (dict of {str: list of str}) -> dict of {str: int}

    The table_to_foods dict has table names as keys (e.g., 't1', 't2', and so on) and each value
    is a list of foods ordered for that table.

    Return a dictionary where each key is a food from table_to_foods and each
    value is the quantity of that food that was ordered.

    >>> get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']})
    {'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3}    
    """

    food_to_quantity = {}

    # Accumulate the food information here.
    # I have no idea what it should be at here.

    return food_to_quantity

How can I write this code correctly? When I use tuple, I try it but I have no idea how to count the times.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46
Polsop
  • 175
  • 3
  • 11

4 Answers4

6
from collections import counter
from itertools import chain
Counter(chain(*table_to_foods.values()))

but im not sure your teacher will accept this ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
2

You'll want to iterate over the items in the values of your dictionary supplied to the function, and add them to your counting dictionary.

def get_quantities(table_to_foods):
    food_to_quantity = {}
    for table_order in table_to_foods.itervalues():
        for menu_item in table_order:
            if menu_item in food_to_quantity:
                food_to_quantity[menu_item] += 1
            else:
                food_to_quantity[menu_item] = 1

    return food_to_quantity

If you can use something other than the bare basics, I would use the approach supplied by Joran with collections.Counter and itertools.chain.from_iterable.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46
0

simple usage of Counter class from collections module:

>>> def get_quantities(table_to_foods):
    c = Counter()
    for li in table_to_foods.values():
        c.update(li)
    return dict(c)
>>> get_quantities(l1)
{'Steak pie': 3, 'Poutine': 2, 'Vegetarian stew': 3}
R Nar
  • 5,465
  • 1
  • 16
  • 32
0
import collections

orders = {'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 
          't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 
          't4': ['Steak pie', 'Steak pie']}

# We're not interested in the table numbers so can initially just produce
# a flat list.

flatorders = []
for o in orders:
    flatorders += orders[o]

quantities = collections.Counter(flatorders)

# The "sorted" keyword prints the list in alphabeitcal order. If it is
# omitted the list is printed in order of quantities.

for k in sorted(quantities):
    print("{:15} {:3d}".format(k, quantities[k]))
TimGJ
  • 1,584
  • 2
  • 16
  • 32