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:25
for i in range(n):
    data = input().split(' ')
    d[data[0]] = data[1]
for keys,values in d.items():
    print(keys)
    print(values)
查看更多
仙女界的扛把子
3楼-- · 2020-05-24 06:28
record = int(input("Enter the student record need to add :"))

stud_data={}

for i in range(0,record):
    Name = input("Enter the student name :").split()
    Age = input("Enter the {} age :".format(Name))
    Grade = input("Enter the {} grade :".format(Name)).split()
    Nam_key =  Name[0]
    Age_value = Age[0]
    Grade_value = Grade[0]
    stud_data[Nam_key] = {Age_value,Grade_value}

print(stud_data)
查看更多
【Aperson】
4楼-- · 2020-05-24 06:32

I have taken an empty dictionary as f and updated the values in f as name,password or balance are keys.

f=dict()
f.update(name=input(),password=input(),balance=input())
print(f)
查看更多
劫难
5楼-- · 2020-05-24 06:35
n = int(input())          #n is the number of items you want to enter
d ={}                     
for i in range(n):        
    text = input().split()     #split the input text based on space & store in the list 'text'
    d[text[0]] = text[1]       #assign the 1st item to key and 2nd item to value of the dictionary
print(d)

INPUT:

3

A1023 CRT

A1029 Regulator

A1030 Therm

NOTE: I have added an extra line for each input for getting each input on individual lines on this site. As placing without an extra line creates a single line.

OUTPUT:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-05-24 06:36

using str.splitines() and str.split():

In [126]: strs="""A1023 CRT
   .....: A1029 Regulator
   .....: A1030 Therm"""

In [127]: dict(x.split() for x in strs.splitlines())
Out[127]: {'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

str.splitlines([keepends]) -> list of strings

Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

str.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

查看更多
Fickle 薄情
7楼-- · 2020-05-24 06:36

This is what we ended up using:

n = 3
d = dict(raw_input().split() for _ in range(n))
print d

Input:

A1023 CRT
A1029 Regulator
A1030 Therm

Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
查看更多
登录 后发表回答