Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple values in a dictionary python

I have data in following form (saved in a list)

id, price, date, category

Now, I basically want to seperate items based on the category.. basically a dictionary where key is the category and rest of the stuff (id, price, data) are its values I have already created a datastructure so lets a datastructre 'item' has the above four stated attributes (id, price, date, category) So basically what i want is a dictionary in following form:

{1: [item_1,item_2....], 2:[item....]} 

how do i do this.. Since there are many values in a single key hence i know that it will use defaultdict.. but still I am not able to get around this. Thanks

like image 504
frazman Avatar asked Dec 30 '25 14:12

frazman


1 Answers

I think you want something like this, assuming your current data is stored in the list list_data:

dict_data = defaultdict(list)
for item in list_data:
    dict_data[item.category].append(item)

If each item is a tuple instead of an object, use item[3] instead of item.category.

like image 60
Andrew Clark Avatar answered Jan 02 '26 08:01

Andrew Clark