Hanwool Codes RSS Tag Admin Write Guestbook
2023-03-10 05:50:32

Collections.OrderedDict() | HackerRank

 

Collections.OrderedDict() | HackerRank

Print a dictionary of items that retains its order.

www.hackerrank.com

Goal

 

You are the manager of a supermarket.
You have a list of N items together with their prices that consumers bought on a particular day.
Your task is to print each item_name and net_price in order of its first occurrence.

 

Solution

 

You use collections.OrderedDict() function to solve this task.

Thid script reads an integer value n from standard input, which represents the number of items in the dictionary.

A loop then runs n times to read item names and their corresponding net prices from standard input. 

The input is split into words, and the script checks if each word is numeric or not.

If the word is numeric, the script assigns it to the net_price variable,

otherwise, it appends it to a list called item_name.

After iterating over the words, the item_name list is joined to create a string representation of the item name. 

Then, the script checks if the item name already exists in the ordered_dictionary

If it does, the script adds the new net price to the existing net price of the item. 

Otherwise, the script creates a new key-value pair in the ordered_dictionary.


Finally, the script iterates over the ordered_dictionary and prints each item name and its net price

Since OrderedDict() maintains the order of the keys, the items are printed in the same order 

in which they were inserted into the dictionary.

# Collections.OrderedDict()

# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict

ordered_dictionary = OrderedDict()

n = int(input())

for i in range(n):
    
    item_name = []
    net_price = 0
    
    for x in input().split():
        if x.isnumeric():
            net_price = int(x)
        else:
            item_name.append(x)
            
    item_name = " ".join(item_name)
            
    if item_name in ordered_dictionary:
        ordered_dictionary[item_name] += net_price
        
    else:
        ordered_dictionary[item_name] = net_price


for k, v in ordered_dictionary.items():
    print(k, v)
Hanwool Codes. Designed by 코딩재개발.