我有一本字典,我不知道如何将提取的变量存储回我的字典中,以便我可以返回字典。
data = """Amanda:100
Katie:90
Eric:78
Mike:45
Paul:71"""
这是给出的数据。
# write a function parseData() which:
# parses the initial data (data),
# stores them in a dictionary, and
# returns the dictionary to the caller.
# The student name must be the key of the dictionary, and
# the student grade its corresponding value
我创建了这个函数并添加了空字典。
def parseData():
# Initialize an empty dictionary.
students = dict()
# After initializing the dictionary, scan all the lines of the data string provided.
infos = data.split('\n')
print infos
# For each line that you get, extract the student and the student scores from that line and
# store it in a two variables: name and scores
for info in infos:
names = info.split(':')
print names
name = names[0]
score = names[1]
print score
students[name] = score
这是我被困的地方。为了存储变量,我想把它放在:
# Store the extracted variables name and scores in the dictionary initialized in and
# return that dictionary
students[info] = score()[info]
return students
答案 0 :(得分:0)
您可以像这样使用dict
构造函数
print dict(line.split(":") for line in data.splitlines())
# {'Paul': '71', 'Mike': '45', 'Amanda': '100', 'Eric': '78', 'Katie': '90'}
这可以写成
result = {}
for line in data.splitlines():
splitted_values = line.split(":")
result[splitted_values[0]] = splitted_values[1]
print result