top of page

Python: Ordered Dictionary - Another HackerRank Solution

Sep 5

2 min read

0

12

0

ree

Reference HackerRank problem: Collections.OrderedDict() | HackerRank



Given an input such as the following:



ree


















Could you output the following:


ree











That is to say, could you output the items as they appear with the cumulative amount spent on each item?


The sticking point here is that the items must appear in the order that they first appear in the input().


To accomplish this, we will used an ordered dictionary which retains the order of the key values added to the dictionary.


For simplicity the code is available below:


ree

The first thing we do is import the OrderedDict method from collections.

Then, we initialize an Ordered Dictionary termed item_dictionary.

We read in the number of lines into a variable N.

We loop through the input that many times and place the item and amount in a list.

There is some list comprehension required as the item can be one word or two words.

Then we use the negative method to assign the value at the end of the list to the variable called value.

This negative method was required as the list could have had a length of 3 or 2.

If the key exists in the item_dictionary add the value to the existing value, if it doesn't just place the value in the dictionary.

Finally, just use the items() method to return the item and the quantity.


Script below for ease of use:


from collections import OrderedDict

item_dictionary = OrderedDict()

N = int(input())


for i in range(N):

list_item = (input().split())

if len(list_item) == 3:

key = (list_item[0] + ' ' + list_item[1])

else:

key = (list_item[0])

value = int(list_item[-1])

if key in item_dictionary:

item_dictionary[key] += value

else:

item_dictionary[key] = value

for item, quantity in item_dictionary.items():

print(item, quantity)


Sep 5

2 min read

0

12

0

Related Posts

Comments

Share Your ThoughtsBe the first to write a comment.
bottom of page