Home > Blockchain >  Python mapping dictionary to a list
Python mapping dictionary to a list

Time:05-16

I have two lists:

prices = [0, 5, 10, 15, 20, 25]

items = [
    {
        “name” : “foo”,
        “price”: 12.3
    }
    {
        “name” : “foo1”,
        “price”: 12.7
    }
    {
        “name” : “foo2”,
        “price”: 20.4
    }
]

I am looking to order items based on the prices, so the result should be something like this:

result = {
    “<5”: [],
    “<10”: [],
    “<15”: [
        {
            “name” : “foo1”,
            “price”: 12.7
        }
        {
            “name” : “foo”,
            “price”: 12.3
        }
    ],
    “<20”: [],
    “<25”: [
        {
            “name” : “foo2”,
            “price”: 20.4
        }
    ],
    “>25”: []
}

So I have made a double loop which works, but I don't think it is super efficient and python way

result = []
for i in range(0, len(prices) - 1):
   itm_list = []
      for f in items:
         if f['price'] > prices[i] and f['price'] <= prices[i 1]:
            itm_list.append(f)
      result.append({f'<{prices[i 1]}': sorted(itm_list, key=lambda k: k['price'], reverse=True)})

CodePudding user response:

As the given input:

items = [
    {"name": "foo", "price": 12.3},
    {"name": "foo1", "price": 12.7},
    {"name": "foo2", "price": 20.4},
]

prices = [0, 5, 10, 15, 20, 25]

Initialize a dictionary result. Iterate over all the prices, get the price range, and append all the items that fit the price range.

result = {}

for i in range(1, len(prices)):
    mn = prices[i - 1]
    mx = prices[i]

    # append all items with price in range
    result["<"   str(mx)] = [item for item in items if item["price"] < mx and item["price"] >= mn]

result[">"   str(prices[-1])] = [item for item in items if item["price"] > prices[-1]]

CodePudding user response:

You can manually iterate through the dictionaries to achieve linear time complexity:

from operator import itemgetter


result = {f'<{price}': [] for price in prices}
dicts = iter(sorted(items, key=itemgetter('price')))
try:
    d = next(dicts)
    for price in prices:
        lst = result[f'<{price}']
        while d['price'] < price:
            lst.append(d)
            d = next(dicts)
except StopIteration:
    result[f'>{price}'] = []
else:
    result[f'>{price}'] = list(dicts)
  • Related