将项目放在文件中的dict中?

时间:2016-06-05 19:15:35

标签: python python-3.x dictionary

如果我有这样的文件:

1000:80
200:90
400:60

我如何将这些值放在dict中?像这样:

 d = {'1000':80, '200:90', '400':60}

1 个答案:

答案 0 :(得分:0)

像这样(使用generator expressionsdictionary comprehension):

with open("myfile.txt") as f:
    my_dict = {x: int(v) for x, v in (line.split(":") for line in f)}

print(my_dict)
  

{'200':90,'400':60,'1000':80}