看起来很简单,但很难实现,想要用只有一条Python语句从由空格分隔的[key, value]对输入中构建一个字典。这是我目前为止的代码:
d={}
n = 3
d = [ map(str,raw_input().split()) for x in range(n)]
print d
输入:
A1023 CRT
A1029 Regulator
A1030 Therm
期望输出:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
看起来很简单,但很难实现,想要用只有一条Python语句从由空格分隔的[key, value]对输入中构建一个字典。这是我目前为止的代码:
d={}
n = 3
d = [ map(str,raw_input().split()) for x in range(n)]
print d
输入:
A1023 CRT
A1029 Regulator
A1030 Therm
期望输出:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
这就是我们最终采用的方案:
n = 3
d = dict(raw_input().split() for _ in range(n))
print d
输入:
A1023 CRT
A1029 Regulator
A1030 Therm
输出:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
使用str.splitlines()
和str.split()
:
strs="""A1023 CRT
A1029 Regulator
A1030 Therm"""
dict(x.split() for x in strs.splitlines())
结果:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
更多信息:
str.splitlines([keepends]) -> 字符串列表
返回字符串S中的行列表,以行边界进行分隔。除非给出 keepends 并为真,否则换行符不包含在结果列表中。
str.split([sep [,maxsplit]]) -> 字符串列表
使用 sep 作为分隔符字符串,返回字符串 S 中的单词列表。如果给定 maxsplit,则最多进行 maxsplit 次拆分。如果未指定 sep 或为 None,则任何空格字符串都是分隔符,并且从结果中删除空字符串。
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)
for i in range(n):
data = input().split(' ')
d[data[0]] = data[1]
for keys,values in d.items():
print(keys)
print(values)
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)
输入:
3
A1023 CRT
A1029 Regulator
A1030 Therm
注意:我为每个输入添加了额外的一行,以便在此网站上将每个输入放在单独的行上。如果没有额外的一行,则会创建一行。
输出:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
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)
s
中的文本:dict(map(lambda l: l.split(), s.splitlines()))
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)
d = {}
count = 0
data = int(input("How many data do you want to enter?(numbers only): "))
while count < data:
count = count + 1
print("Enter a key")
key = input()
print("Enter a value")
value = input()
d[key] = value
if count >= data:
break
print(d)
我已经创建了一个空字典f,并将其更新为以“name”、“password”或“balance”为键的值。
f=dict()
f.update(name=input(),password=input(),balance=input())
print(f)