Reputation: 2857
I have a list of lists, each list has 3 items in it (for the sake of the example): product type, product color, quantity of product.
What I'm trying to do is to create a dictionary in a way that each product type is a key, and the color and quantities are values. That is, what I'm looking for is this structure:
key1:(tuple1),(tuple2),...
or
key1:[(tuple1),(tuple2),...]
The thing is, as you know, you can't really append tuples as values to keys in dicts.
Here's a simple example to play around with:
my_list = [["ball","red",2],["ball","blue",5],["ball","green",7],["shirt","large",5],["shirt","medium",9],["shirt","small",11]]
inventory_dict = {}
for item in my_list:
if item[0] not in inventory_dict:
inventory_dict[item[0]] = (item[1],item[2])
else:
inventory_dict[item[0]].append((item[1],item[2]))
When I tried to do something like:
my_list = [["ball","red",2],["ball","blue",5],["ball","green",7],["shirt","large",5],["shirt","medium",9],["shirt","small",11]]
inventory_dict = {}
for item in my_list:
my_tuple = (item[1],) + tuple(item[2])
if item[0] not in inventory_dict:
inventory_dict[item[0]] = my_tuple
else:
inventory_dict[item[0]].append(my_tuple)
inspired by this answer I got a "TypeError: 'int' object is not iterable" error.
and when I tried to replace my_tuple with:
my_tuple = list((item[1],item[2]))
inspired by this answer I got a result I can't work with, of this form:
{'ball': ['red', 2, ['blue', 5], ['green', 7]],
'shirt': ['large', 5, ['medium', 9], ['small', 11]]}
the reason I can't work with it is that for example the len of each value is 4 where it should be 3. The first type and its quantities are separate elements of the value list.
I should mention that in the next step of my code I plan on doing some asthmatics with the quantities.
Hope I was able to explain my problem well enough and hope you can help! Thanks :)
Upvotes: 1
Views: 6066
Reputation: 251353
Change the line in your first example to:
inventory_dict[item[0]] = [(item[1],item[2])]
If you want to be able to append things later, you need to make the value a list the first time you create it.
You could also use collections.defaultdict
, which would let you just do:
inventory_dict = collections.defaultdict(list)
and then you can dispense with the if-then and just do the loop like this:
for item in my_list:
inventory_dict[item[0]].append((item[1], item[2]))
Upvotes: 5