Collections.OrderedDict()

  • + 45 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)
    
    • + 2 comments

      me too but I think yours is more clear:

      from collections import OrderedDict
      dct = OrderedDict()
      for _ in range(int(input())):
          i = input().rpartition(" ")
          dct[i[0]] = int(i[-1]) + dct[i[0]] if i[0] in dct else int(i[-1])
      for l in dct:
          print(l, dct[l])
      

      get() works much better.

      • + 3 comments

        can you please explain 5th line (if else on the same line)?

        • + 1 comment

          dct[i[0]] = int(i[-1]) + dct[i[0]] if i[0] in dct else int(i[-1])

          B if A else C does a conditional evaluation: if A evaluates to truth, then the value of the expression is B, else it evaluates to C.

          So what it's saying is: if i[0] (the name of the item) is a key in dct, then the value is int(i[-1]) + dct[i[0]]. If it is not a key in dct, then the value is int(i[-1])

          if could still be used, but xpressed a bit shorter as

          dct[i[0]] = int(i[-1]) + (dct[i[0]] if i[0] in dct else 0)

          But DICT[SOMETHING] if SOMETHING in DICT else DEFAULT already has a function for it, because it happens so often: DICT.get(SOMETHING, DEFAULT)

          • + 0 comments

            here is solution of problem Collections.OrderedDict() in python 2 and python 3 https://solution.programmingoneonone.com/2020/06/hackerrank-collections-ordereddict-problem-solution-python.html

        • + 0 comments

          here is problem solution in python programming. https://programs.programmingoneonone.com/2021/01/hackerrank-collections-ordereddict-solution-python.html

        • + 0 comments

          Updated solution is here

          https://www.thecscience.com/2021/08/HackerRank-Collections.OrderedDict-in-python-problem-solution.html

      • + 2 comments

        this code is highly unreadble and way more complex than the answer needs to be. Will suggest people to avoid doing it this way

        • + 4 comments

          That's why I prefer clean, efficient and elegant solution which can be found here. Hackerrank OrderedDict clean solution

          • + 0 comments

            For easy solution and explanation please refer to this link. Have a good day https://codingsolutions4u.blogspot.com/2020/09/collections-ordereddict-hackerrank.html

          • + 0 comments

            For easy solution and explanation please refer to this link. Have a good day https://codingsolutions4u.blogspot.com/2020/09/collections-ordereddict-hackerrank.html

          • + 0 comments

            Found one critical bug, your site doesn't work in dark mode, thank me later

          • + 0 comments

            Your links don't work

    • + 1 comment

      rpartition is pretty handy. thanks

    • + 4 comments

      You can remove one more line by doing the print in 1 line:

      from collections import OrderedDict
      D = OrderedDict()
      for _ in range(int(input())):
          item, space, price = input().rpartition(' ')
          D[item] = D.get(item, 0) + int(price)
      print(*[" ".join([item, str(price)]) for item, price in D.items()], sep="\n")
      
      • + 1 comment

        No need for list inside of print, you can use a generator

        • + 1 comment

          Mera lauda

          • + 0 comments

            kitna bada h

      • + 1 comment

        from where u learn all thesae things bro

        • + 1 comment

          mera l****

          • + 0 comments

            lol

      • + 0 comments

        Nice coding!!

      • + 0 comments

        The print can be changed to:

        [print(*i) for i in D.items()]

    • + 1 comment

      perhaps earning a variable:

      item, quantity = input().rsplit(None, 1)
      
      • + 1 comment

        lol i used re

        import re; item,prize = re.split(r'\s+(?=\d+$)',input())

        • + 0 comments

          show off bro show off :P

    • + 6 comments

      I did pretty much the same but I didn't know about rpartition or rsplit, so I went for this instead:

      line = raw_input().split()
      item, price = ' '.join(line[:-1]), int(line[-1])
      
      • + 1 comment

        me too, they are so geeky

        • + 1 comment

          bhag madharjaat

          • + 0 comments

            stop trying to be an asshole so hard. You are failing miserably.

      • + 2 comments

        please explain your code! or mention it here let me understand

        • + 0 comments

          line = ['banana', 'fries', '10'] line[:-1] returns the list upto the second last word ['banana', 'fries'] performing a join on it returns a string 'banana fries' item maps to the name, which is a string price maps to the price which is the last element in line, refered by line[-1]

        • + 0 comments

          bsdk pythojn docs me padh le

      • + 1 comment

        wah lauda tumne to bur me jhande gar diye

        • + 0 comments

          Randi kahana me paida hua h kya gali hi bakta h.....

      • + 0 comments

        There could be a problem. Suppose that the input were

        Dancing___Monkeys___10

        where each _ represents one space. You would getDancing_Monkeys as the item name, because the full split would get rid of all three spaces but you'd only put one back. rsplit(1) would get an item name of Dancing___Monkeys with three spaces.

      • + 0 comments

        can anyone explain the 2nd line??

      • + 0 comments

        lst=input().split()

        quantity=lst.pop()

        item=' '.join(lst)

    • + 1 comment

      Sorry, can you explain how to use d.get(item,0)?

      • + 0 comments

        get() returns the value associated with the key "item". If the key doesn't already exist, then it will return the "default" value (written on the right side of comma - 0) instead. So if it already exists, then it will add the previous price. Otherwise, it will add 0 to the new number.

    • + 0 comments

      I could not understand use of space and can item as key can have space in it. It must be right as this is working perfectly. But

    • + 0 comments

      plz can u explain line by line

    • + 1 comment

      what rpartition does here?

      • + 0 comments

        http://python-reference.readthedocs.io/en/latest/docs/str/rpartition.html

        it seems to form a tuple containing 3 parts: 1. the portion of string before the determined separator ( in this case the ' ' which is a space) 2. the determined separator itself 3. the portion of string after the determined separator

        Based on the example, it seems like it will pick the separator that appeared last so in this case, it will choose the space before the integer :)) Hope I helped ans your qns lol

    • + 1 comment

      Thanks for rpartition, quite useful. Before it, I did:

      from collections import OrderedDict
      
      def convert(val):
          m = {
                  list: lambda x: " ".join(x),
                  str: lambda x: int(x)
              }
          return m[type(val)](val)
      
      d = OrderedDict()
      num_items = int(input())
      
      for _ in range(num_items):
          *head, tail = input().split()
          item_name, item_price = map(lambda x: convert(x), [head, tail])
          d[item_name] = d.get(item_name, 0) + item_price
      
      for k, v in d.items():
          print(k,v)
      

      After knowing learning about it, I arrived at pretty the same solution as you.

      from collections import OrderedDict
      
      d = OrderedDict()
      num_items = int(input())
      
      for _ in range(num_items):
          item_name, _, item_price = input().rpartition(' ')
          d[item_name] = d.get(item_name, 0) + int(item_price)
      
      for k, v in d.items():
          print(k,v)
      
      • + 1 comment

        You can use simple unpacking for the item name like this:

        from collections import OrderedDict
        od = OrderedDict()
        for i in range(int(input())):
          *item, price = input().split()
          item = ' '.join(item)
          od.setdefault(item, 0)
          od[item] = od[item] + int(price)
        for k,v in od.items():
          print(k + ' ' + str(v))
        
        • + 0 comments

          how asterisk help to remove ....too many values to unpack this error

    • + 0 comments

      nice :D rpartition :))

    • + 1 comment

      You could use rsplit with limit 1 instead of rpartition.

      • + 0 comments

        same thing i thought

    • + 0 comments

      what d.get(item,0) does

    • + 0 comments

      +1 for

      input().rpartition(' ')
      d.get(item, 0)
      
    • + 0 comments

      Get method is pretty awesome.

    • + 0 comments

      Can you please explain me this. I am new to python. I am unable to fathom the operations that are being performed here on tuples and dictionaries.

    • + 0 comments

      In your code of OrderedDict,
      Can you tell me the work of** d.get(item, 0)**

    • + 0 comments

      Hey, can you plz tell why it is not taking first element as " " as we have no item with 9

    • + 0 comments

      superb way of thinking bro

    • + 0 comments

      why is 'space' used?

    • + 0 comments

      I don't get the "space" part?

    • + 0 comments

      can you please explain line 5 - d[item] = d.get(item, 0) + int(quantity)

      I could not get "d.get(item, 0) " part

    • + 0 comments

      even working without OrderedDict no need to import collections

    • + 1 comment

      Could you please explain what is this line of code perfoming d[item] = d.get(item, 0) + int(quantity)

      • + 0 comments

        This get method returns the value for the given key, if present in the dictionary.

    • + 0 comments

      I made it in 6 :

      from collections import OrderedDict
      dic = OrderedDict()
      for _ in range(int(input())):
          item,price = input().rsplit(maxsplit=1)
          dic[item] = dic.get(item, 0) + int(price)
      print(*[f'{item} {dic[item]}' for item in dic.keys()], sep='\n')
      
    • + 0 comments

      can you please explai your code @jonmcclung

    • + 1 comment

      Try my method by using defaultdict

      **from collections import*

      a=defaultdict(list)

      for q in range(int(input())):

      item,space,quantiy=input().rpartition(" ")

      a[item].append(int(quantiy))

      for w,e in a.items():

      print(w,sum(e))

      **

      • + 1 comment

        Traceback (most recent call last): File "Solution.py", line 5, in item,space,quantiy=input().rpartition(" ") File "", line 1 BANANA FRIES 12 ^ SyntaxError: invalid syntax YOUR CODE IS GIVING THIS ERROR.CAN U PLZ TELL ME HOW TO REMOVE IT.

        • + 0 comments

          no men my code is perfectly working. i think you have make some type of the syntex error. Can you please send me your full code.

    • + 0 comments

      Great

    • + 1 comment

      can you explain line 5 ?

      • + 0 comments

        in line 5 you will append the item in the type of the list . if the item is same then the quantity will be added as a list of items .

        and if the item is not same then then it will append the items as a simple list .

    • + 0 comments

      why have you used "space" identifier in 4th line

    • + 1 comment

      d[item] = d.get(item, 0) + int(quantity)

      Can you explain this? Thanks in advance

      • + 1 comment

        d.get(item,0) = means you have to search no(item) if you not get the the same no than 0 will be added. and if you get then it will be added in int(quantity)

        I make 0 as a default case .. you can also use orderdict if you can not mind it.

        • + 0 comments

          yup,thanks for giving the suggestion

    • + 0 comments

      what is function of odereddict in this code, can anyone explain it??

    • + 0 comments

      good man

    • + 0 comments

      can u pls explain 5th line

    • + 0 comments

      I tried printing d and d.items, the output looks the same but if i try to replace for item, quantity in d.items(): to for item, quantity in d: it doesn't work. Why?

    • + 0 comments

      Can you please explain the 5th line !

    • + 1 comment

      can u please explain the function of _ in for loop

      • + 2 comments

        For _ in range(int(input())): '_' is just an placeholder variable.

    • + 0 comments

      This problem with Collections.OrderedDict() is instructive. I must say this is very useful for students. cheap CBD We all know the importance of maths in our education system. This section helps the students to learn maths in a very interesting way.

    • + 0 comments

      For this question, simple dictionary was fine. Because the items listed already in the order. OrderedDict will be usefull for other scenarios. rpartition helps me

    • + 2 comments

      When used rpartition and given sepererator as ' ', I know a tuple is created which also includes ' ', for instance BANANA FRIES 30, output will be ('BANANA FRIES', ' ', '30'), can someone explain why this does not appear in Ordered Dictonary?

      • + 0 comments

        In this case no need of orderdict, you have to print the output in the order of customers baught the item which is already in the order. Please refer the following link to get know about Ordered Dict https://docs.python.org/3/library/collections.html#collections.OrderedDict

    • + 1 comment

      rpartition(' ') whats this?

      • + 0 comments
        item_name, part, item_price ='NON_PARTITIONED_RIGHTSPLIT FRIES PARTITIONED_RIGHTSPLIT 12'.rpartition('RIGHTSPLIT')
        print(item_name,part,item_price)
        output => ('NON_PARTITIONED_RIGHTSPLIT FRIES PARTITIONED_', 'RIGHTSPLIT', ' 12')
        

        i.e It is spliting based on rightside occurance of string

    • + 0 comments
      • from collections import OrderedDict
      • d = OrderedDict()
      • for _ in range(int(input())):
      • item, quantity = input().rsplit(None, 1)
      • d[item] = d.get(item, 0) + int(quantity)
      • for item, quantity in d.items():
      • print(item, quantity)

      use rplit instead of rpartition. this way you don't need to save space

    • + 0 comments

      Thanks! it worked! But why are we using rpartition? Why can't we use just input().split for item and quantity. The next input is anway in the next line and we are already using a for loop

    • + 0 comments

      genius!

    • + 0 comments

      Thanks bro, it helped me to learn about rpartition function and get func in dictinoary!