Python Dictionary Fill

Hey. I create a dictionary where each key is the name of the client, and each value is a list of tuples that are bought by each client, for example: (product, quantity). For example:

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

I populate a dictionary based on the results of an SQL query. As a Java programmer new to Python, can anyone suggest a β€œpythonic” way to do this? Each line from the request contains the customer name, product, quantity.

+8
python dictionary
source share
5 answers

First of all, I would use lists, not tuples, as dictionary entries. The main difference is that lists are mutable, but tuples are not.

I think defaultdict is suitable for this problem:

 from collections import defaultdict customers = defaultdict(list) 

You can add such entries (of course, in your case you will do this in a loop):

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

Result:

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

Your internal structure should be a list, not a tuple, as the structure is homogeneous.

 {'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 each value with an empty list for further simplification.

+1
source share

I hope you have a list of lists from your database, for example,

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

Then you can just do it.

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

Here is what I would 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) 

What seal

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

You can use the built-in defaultdict and create an instance in the form of a list and add the fields that you want to use in your loop, for example. if you need the whole row except the first element, you can do your_defaultdict_instance[row[0]].append(row[1:]) , which will neatly create everything.

0
source share

All Articles