简体   繁体   中英

grouping dictionary with list values

I have a dictionary where lists are values. I would like to filter the data based on certain values within lists. For example. . .

inventory = {'A':['Toy',3], 'B':['Toy',8], 'C':['Cloth',15], 'D':['Cloth',9], 'E':['Toy',11]}

I would like to create another dictionary where it only shows the top priced item such that it will be. . .

inventoryFiltered = {'C':['Cloth',15], 'E':['Toy',11]}

What code should I use to convert inventory into inventoryFiltered?

The end result should have top priced for each merchandise item type (such as 'Cloth', 'Toy', 'Electronic', 'Food', 'Shoes')

I only have these modules available for my system.

bisect
cmath
collections
datetime
functools
heapq
itertools
math
numpy
pandas
pytz
Queue
random
re
scipy
statsmodels
sklearn
talib
time
zipline

Further, I would like to accomplish one more step. Say I have one more data element (I am adding the item's days in inventory (how many days it was on the store or storage).

inventory = {'A':['Toy',3, 30], 'B':['Toy',8, 40], 
    'C':['Cloth',15, 50], 'D':['Cloth',9, 60], 'E':['Toy',11, 70]}.  

I would like it to do the exact same thing. But keep the last element (days in inventory)

inventoryFiltered = {'C':['Cloth',15, 50], 'E':['Toy',11, 70]}

You can sort on the items of the dictionary:

inventory = {
    'A': ['Toy', 3, 30],
    'B': ['Toy', 8, 80],
    'C': ['Cloth', 15, 150],
    'D': ['Cloth', 9, 90],
    'E': ['Toy', 11, 110]
}

items = sorted(inventory.items(), key=lambda item: item[1][1])

most_expensive_by_category = {item[0]: (key, item) for key, item in items}

most_expensive = dict(most_expensive_by_category.values())

Result:

{'C': ['Cloth', 15, 150], 'E': ['Toy', 11, 110]}

With items = sorted(inventory.items(), key=lambda item: item[1][1]) we sort the items of input dictionary by price. Because of the sort order, most_expensive_by_category construction will keep only the most expensive item for a specific category.

I would first invert the dictionary like so:

inv={}
for k, li in inventory.items():
    inv.setdefault(li[0], []).append([k, li[1]])

>>> inv
{'Cloth': [['C', 15], ['D', 9]], 'Toy': [['A', 3], ['B', 8], ['E', 11]]}

Then getting the max of any category is trivial:

>>> max(inv['Cloth'], key=lambda l: l[1])
['C', 15]
>>> max(inv['Toy'], key=lambda l: l[1])
['E', 11]
>>> {k:max(inv[k], key=lambda l: l[1]) for k,v in inv.items()}
{'Cloth': ['C', 15], 'Toy': ['E', 11]}

If you have a second element, like days of age, just use that in the max key value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM