将文本文件制作成字典PYTHON

时间:2014-12-08 17:52:08

标签: python dictionary

我想将此文本文件转换为字典,但它似乎不起作用。

eggs 5
spam 3
cool 2
yolk 3
milk 5

def openspam():
     badwordsfile = open("FulaOrd0.txt","r", encoding="utf-8")
     for words in badwordsfile:
          d = {}
          word, value = words.rstrip().split(None, 1)
          d[word] = value
     return d

d = openspam()

当我检查shell中是什么" d"时。我得到了" {"牛奶":5}。我想得到{"鸡蛋":5,"垃圾邮件":3,"酷":2,"蛋黄":3,& #34;牛奶":5}

有人看到我做错了吗?

1 个答案:

答案 0 :(得分:5)

d = {}移到循环之外。否则,您将在每次迭代期间删除其内容。

def openspam():
     badwordsfile = open("FulaOrd0.txt","r", encoding="utf-8")
     d = {}
     for words in badwordsfile:
          word, value = words.rstrip().split(None, 1)
          d[word] = value
     return d

d = openspam()