Make a dictionary in Python from input values

2020-05-24 05:57发布

Seems simple, yet elusive, want to build a dict from input of [key,value] pairs separated by a space using just one Python statement. This is what I have so far:

d={}
n = 3
d = [ map(str,raw_input().split()) for x in range(n)]
print d

Input:

A1023 CRT
A1029 Regulator
A1030 Therm

Desired Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

9条回答
太酷不给撩
2楼-- · 2020-05-24 06:42

Assuming you have the text in variable s:

dict(map(lambda l: l.split(), s.splitlines()))
查看更多
Deceive 欺骗
3楼-- · 2020-05-24 06:44
n=int(input())
pair = dict()

for i in range(0,n):
        word = input().split()
        key = word[0]
        value = word[1]
        pair[key]=value

print(pair)
查看更多
狗以群分
4楼-- · 2020-05-24 06:48
n = int(input("enter a n value:"))
d = {}

for i in range(n):
    keys = input() # here i have taken keys as strings
    values = int(input()) # here i have taken values as integers
    d[keys] = values
print(d)
查看更多
登录 后发表回答