JCB
JCB

Reputation: 1857

Populating a Python dictionary

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.

Upvotes: 9

Views: 31010

Answers (5)

Christian Witts
Christian Witts

Reputation: 11585

You can use the built-in defaultdict and instantiate it as a list, and append the fields you want to it in your loop, for eg. if you wanted the entire row except the first element you could do your_defaultdict_instance[row[0]].append(row[1:]) which will neatly build everything up.

Upvotes: 0

NPE
NPE

Reputation: 500427

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)]}

Upvotes: 13

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

Your inner structure should be a list, not a tuple, since the structure is homogenous.

{'customer1': [('milk', 3), ('bread', 5), ('eggs', 2)],
 'customer2': [('cheese', 2), ('cereal', 7)]}

This will also allow you to use .append() on them, and you can use collections.defaultdict to start off each value with an empty list for further simplification.

Upvotes: 2

Nick Craig-Wood
Nick Craig-Wood

Reputation: 54089

Here is what I'd do

from collections import defaultdict

data = (
    ('customer1', 'milk', 3),
    ('customer1', 'bread', 5),
    ('customer1', 'eggs', 2),
    ('customer2', 'cheese', 2),
    ('customer2', 'cereal', 7),
    )

result = defaultdict(list)
for name, what, amount in data:
    result[name].append((what, amount))

from pprint import pprint
result = dict(result)
pprint(result)

Which prints

{'customer1': [('milk', 3), ('bread', 5), ('eggs', 2)],
 'customer2': [('cheese', 2), ('cereal', 7)]}

Upvotes: 1

Jakob Bowyer
Jakob Bowyer

Reputation: 34698

Im hoping that you have a list of lists from your database, so e.g.

rows = [('customer1', ('milk', 2)), ('customer12', ('bread', 4))] # etc etc

Then you can simply do.

for row in rows:
    cust_dict[row[0]] = row[1:]

Upvotes: 1

Related Questions