frazman
frazman

Reputation: 33243

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

Upvotes: 2

Views: 5625

Answers (3)

Shawn Chin
Shawn Chin

Reputation: 86864

output = defaultdict(list)
for item, cat in ((x[:-1], x[-1]) for x in data):
    output[cat].append(item)

or, without defaultdict:

output = {}
for item, cat in ((x[:-1], x[-1]) for x in data):
    output.setdefault(cat, []).append(item)

Example output:

>>> data = [
...     (1, 123, "somedate", "boy"),
...     (3, 435, "anotherdate", "boy"),
...     (23, 123, "moredate", "girl"),
... ]
>>> output = {}
>>> for item, cat in ((x[:-1], x[-1]) for x in data):
...     output.setdefault(cat, []).append(item)
... 
>>> print output
{'boy': [(1, 123, 'somedate'), (3, 435, 'anotherdate')], 'girl': [(23, 123, 'moredate')]}

Upvotes: 4

Andrew Clark
Andrew Clark

Reputation: 208475

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.

Upvotes: 4

Morten Kristensen
Morten Kristensen

Reputation: 7613

One way to do it would be to have a dictionary where each value is a list of items (id, price, date) and the key is the category.

Something along the lines of the following, where d is a dictionary, c is a category and itm is a tuple/item:

def insert(d, c, itm):
  if not c in d:
    d[c] = [itm]
  else:
    d[c].append(itm)

Upvotes: 2

Related Questions