Collections.OrderedDict()

Sort by

recency

|

695 Discussions

|

  • + 0 comments

    from collections import OrderedDict n = int(input()) item = OrderedDict()

    for _ in range(n): item_name,price = input().rsplit(' ',1) price = int(price)

    if item_name in item:
        item[item_name] += price
    
    else:
        item[item_name] = price
    

    for item_name,item_price in item.items(): print(f'{item_name} {item_price}')

  • + 0 comments

    def col_net(): n = int(input()) dic = {} lis = [] for _ in range(n): line = input().strip() item,price = line.rsplit(' ',1) price = int(price)

        if item in dic:
            dic[item]['quantity'] += 1
        else:
            dic[item] = {'quantity':1,'price':price}
            lis.append(item)
    
    for item in lis:
       net_price = dic[item]['quantity'] * dic[item]['price']
       print(f"{item} {net_price}")
    

    col_net()

  • + 0 comments

    One of the great features of OrderedDict is that even if you update an existing key with a new value, it doesn't lose its original position in the order. https://bcgame.ind.in/contact/

  • + 0 comments

    Since CPython 3.6, normal dict keep the insertion order. Since Python 3.7, it is a guaranteed language feature. So you can just check the version of Python and use a normal dict instead of an OrderedDict (or better here, a defaultdict) and it will work with all implementations of Python 3.7+. It works on Hackerrank for this exercise, both with a dict and a defaultdict.

  • + 0 comments

    here's my code:

    from collections import OrderedDict
    orders = OrderedDict()
    for i in range(int(input())):
        name, _, price = input().rpartition(' ')
        orders[name] = orders.get(name, 0) + int(price)
    [print(*item) for item in orders.items()]