We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Python
  3. Collections
  4. Collections.OrderedDict()
  5. Discussions

Collections.OrderedDict()

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 460 Discussions, By:

votes

Please Login in order to post a comment

  • jonmcclung
    6 years ago+ 44 comments

    Just 7 lines:

    from collections import OrderedDict
    d = OrderedDict()
    for _ in range(int(input())):
        item, space, quantity = input().rpartition(' ')
        d[item] = d.get(item, 0) + int(quantity)
    for item, quantity in d.items():
        print(item, quantity)
    
    176|
    Permalink
    View more Comments..
  • tunavargi
    6 years ago+ 2 comments
    from collections import OrderedDict
    
    number_ = int(input())
    odict = OrderedDict()
    for i in range(number_):
        litem = input().split(' ')
        price = int(litem[-1])
        item_name = " ".join(litem[:-1])
        if odict.get(item_name):
            odict[item_name] += price
        else:
            odict[item_name] = price
    
    for i,v in odict.items():
        print(i,v)
    
    38|
    Permalink
  • geekypandey
    2 years ago+ 6 comments

    6 lines :-) The dictionaries in latest python are ordered. Check out this talk by Raymond Hettinger.

    store_item = dict()
    for _ in range(int(input())):
        key,_,value = input().rpartition(" ")
        store_item[key] = store_item.get(key,0) + int(value)
    for k,v in store_item.items():
        print(k,v)
    
    19|
    Permalink
    View more Comments..
  • Debsankar_Jana
    5 years ago+ 2 comments
    from collections import OrderedDict
    n, item_list = int(input()), OrderedDict()
    for _ in range(n):
        item, price = input().rsplit(' ',1)    
        item_list.setdefault(item, 0)
        item_list[item] += int(price)
    [print(i, v) for i, v in item_list.items()]
    
    8|
    Permalink
  • marinskiy
    4 years ago+ 3 comments

    Here is Python 3 solution from my HackerrankPractice repository:

    from collections import OrderedDict
    ordered_dictionary = OrderedDict()
    for _ in range(int(input())):
        item, price = input().rsplit(' ', 1)
        ordered_dictionary[item] = ordered_dictionary.get(item, 0) + int(price)
    [print(item, ordered_dictionary[item]) for item in ordered_dictionary]
    

    Feel free to ask if you have any questions :)

    6|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature