Populating a Python dictionary

dictionary, python

Solution

First of all, I'd use lists rather than tuples as dictionary entries. The principal difference is that lists are mutable, whereas tuples are not.

I think `defaultdict` is a good for for this problem:

from collections import defaultdict

customers = defaultdict(list)

You can add entries like so (of course in your case you'd do this in a loop):

customers['customer1'].append(('milk', 3))
customers['customer1'].append(('bread', 5))
customers['customer2'].append(('cereal', 7))

The result is:

>>> print dict(customers)
{'customer1': [('milk', 3), ('bread', 5)], 'customer2': [('cereal', 7)]}

Problem

Hi I'm building a dictionary where each key is a customer name and each value is a list of tuples which are purchased by each customer, like so: (product, quantity). For example: ``` {'customer1': (('milk', 3), ('bread', 5), ('eggs', 2)), 'customer2': (('cheese', 2), ('cereal', 7))} ``` I am populating the dictionary based on the results of a SQL query. Being a Java programmer new to Python, can someone suggest the "pythonic" way to do this? Each row from the query contains customer name, product, quantity.

Original source