Prepare > Python > Collections > Collections.OrderedDict()
Collections.OrderedDict() | HackerRank
Print a dictionary of items that retains its order.
www.hackerrank.com
문제
Task
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.
item_name = Name of the item.
net_price = Quantity of the item sold multiplied by the price of each item.
Input Format
The first line contains the number of items, N.
The next N lines contains the item's name and price, separated by a space.
Output Format
Print the item_name and net_price in order of its first occurrence.
=> N과 N개의 판매 내역을 줄건데, 각 품목별 매출액을 구하라
코드
from collections import OrderedDict
N = int(input())
day_revenue = OrderedDict()
for i in range(N):
sales = input().split()
item_name = ' '.join(sales[:-1])
if item_name not in day_revenue.keys():
day_revenue[item_name] = sales[-1]
else:
day_revenue[item_name] = str(int(day_revenue[item_name]) + int(sales[-1]))
for j in day_revenue.items():
print(' '.join(j))
두 번째 시도
from collections import OrderedDict
N = int(input())
od = OrderedDict()
for i in range(N):
*menu, price = input().split()
menu = ' '.join(menu)
if menu in od.keys():
od[menu] += int(price)
else:
od[menu] = int(price)
for menu, price in od.items():
print(menu, price)
노트
orderdict()
ordered_dictionary = OrderedDict()
ordered_dictionary['a'] = 1
ordered_dictionary['b'] = 2
ordered_dictionary['c'] = 3
ordered_dictionary['d'] = 4
ordered_dictionary['e'] = 5
print(ordered_dictionary)
# OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
- 순서가 있는 dictionary로 생각. dict의 하위 클래스임
- 중괄호{} 와 콜론: 이 쓰이는 dict와는 다름
dict.items()
- dict의 key-value 값을 한 번에 받아오는 메서드
split(maxsplit= )
- 문자열을 쪼갤 때 쪼개는 횟수는 지정할 수 있는 옵션, default는 max임
- 앞에서 부터 쪼갬
참조
[python] 파이썬 split 함수 정리 및 에제 (문자열 쪼개기)
안녕하세요. BlockDMask 입니다. 오늘 알아볼 파이썬 함수는 split 함수 입니다. 문자열을 이쁘게 나눠서 리스트로 만들때 사용하는 함수 입니다. 한번 알아보도록 하겠습니다. 1. split 함수? 2. split 함
blockdmask.tistory.com