2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python3 標準入力を辞書にする方法

Last updated at Posted at 2022-08-31

先日、paizaラーニングのレベルアップ問題集で、連想配列の問題を解いていたときにでた疑問をまとめました。
https://paiza.jp/works/mondai/query_primer/query_primer__map_normal
(この練習問題の自分のコードも最後に載せてあります。)

python3 で 標準入力を辞書の形にする方法

まず、リストを作成し、そこに要素を順に入れていきます。

list_dic = []

for i in range(N):
    list_dic.append(input().split())

そして、dict()を使って辞書にします。

dictionary = dict(list_dic)

例:
標準入力

1 Sin
2 Sakura
3 Kayo
4 Yui

コード

mylist=[]

for i in range(N):
    mylist.append(input().split())

mydict=dict(mylist)

出力

{'1': 'Sin', '2': 'Sakura', '3': 'Kayo', '4': 'Yui'}

参照:https://azuminow.com/python-dictionary

練習問題の自分の解答
# coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!
N,K = map(int,input().split())

mylist=[]

for i in range(N):
    mylist.append(input().split())
    mylist[i][0]=int(mylist[i][0])

mydict=dict(mylist)

#print(mydict)

order = []
for i in range(K):
    order.append(input().split())
    
#print(order)

for j in range(K):
    if order[j][0] == 'leave':
        mydict[int(order[j][1])] = ''
    elif order[j][0] == 'call':
        print(mydict[int(order[j][1])])
    else:
        mydict[int(order[j][1])] = order[j][2]
2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?