use*_*892 0 python dictionary file readline
输入文件如下所示:
A 3.00 B 4.00 C 5.00 D 6.00
E 3.20 F 6.00 G 8.22
H 9.00
I 9.23 J 89.2
K 32.344
Run Code Online (Sandbox Code Playgroud)
我希望字符成为字典中的键,而浮点数是值.
这是我到目前为止的非工作失败.
def main():
#Input File
reader = open('candidate.txt', 'r'
my_dictionary = {}
i=0
for line in reader.readlines():
variable = line.split(' ')[i]
value = line.split(' ')[i+1]
my_dictionary[variable]= value
i+=2
print my_dictionary
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
s='''A 3.00 B 4.00 C 5.00 D 6.00
E 3.20 F 6.00 G 8.22
H 9.00
I 9.23 J 89.2
K 32.344
'''
s=s.split()
d=dict(zip(s[::2], s[1::2]))
print d
Run Code Online (Sandbox Code Playgroud)
在上下文中:
my_dict = dict()
for line in reader.readlines():
pairs = line.split()
for key, value in zip(pairs[::2],pairs[1::2]):
my_dict[key] = value # strip() not needed
Run Code Online (Sandbox Code Playgroud)