0
0

プログラム練習問題:経理

Posted at

ひとまず前回のと同様にしてみたのですが
どうしてもエラーが発生する。


N,K = map(int,input().split())
sections = {input() for _ in range(N)}
print(sections)
for _ in range(K):
    section, number, cost = input().split()
    print(section)
    section, total_cost = sections[section]
    sections[section] = (int(number), total_cost + int(cost))
    
print(sections)

Traceback (most recent call last):
  File "Main.py", line 5, in <module>
    sections[section].append((number,cost))
TypeError: 'set' object is not subscriptable

なぜだ?と思ってたら、最初の辞書のフォーマットを作るところを間違えていたようだ。


#まちがい:これだと辞書にならなくてただの集合になる
sections = {input() for _ in range(N)}

#正しい:キー:値の形になっていて辞書になる
sections = {input():[] for _ in range(N)}

ちなみに、わたしは各部署の合計値を出力するのかと勘違いしてて
そうではなく、各部署のすべての取引をグループごとに出力することが正解だった。
なので正しくはこう。

N,K = map(int,input().split())
sections = {input():[] for _ in range(N)}
for _ in range(K):
    section, number, cost = input().split()
    sections[section].append((number,cost))

for section, value in sections.items():
    print(section)
    for number, cost in value:
        print(number, cost)

    print("-----")

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0