从文件创建字典?蟒蛇

时间:2016-11-23 04:02:42

标签: python dictionary

我正在尝试将文件的内容存储到字典中,我认为我做得对,但它不会打印出所有内容,只是第一行。我不知道我做错了什么,有人可以帮助我吗?

我正在使用的文件(mood.txt):

happy, Jennifer Clause
sad, Jonathan Bower
mad, Penny
excited, Logan 
awkward, Mason Tyme

我的代码:

def bringFile():

    moodFile = open("mood.txt")
    moodread = moodFile.readlines()
    moodFile.close()
    return moodread


def makemyDict(theFile):
    for i in theFile:
        (mood, name) = lines.split(",")

        moodDict = {mood : name}

        #print the dictionary   

        for m in moodDict:
            return(m, name)


def main():

    moodFile = bringFile()

    mDict = makemyDict(moodFile)

    print(mDict)

我正在尝试检查字典是否真的有效,这就是为什么我现在打印出来的原因。每次我尝试打印输出:

('happy', ' Jennifer Clause\n')

我试图把所有的元素分别用在心情/名字里面,以便我以后可以使用它们,但它似乎只打印出一对。我觉得我的所有步骤都是正确的,所以我不知道该怎么办!

谢谢!

4 个答案:

答案 0 :(得分:0)

您正在为每个循环重置整个字典, 使用moodDict[mood] = name只设置一个键值对。

你也在回路内返回,这将完全缩短功能。您应该将for m in moodDict循环移到外循环之外并使用print而不是return,或者只使用函数末尾的return moodDict来打印它们在功能之外。

另外请注意,您可能需要调用mood.strip()name.strip()来删除每个空格。

答案 1 :(得分:0)

你正在for循环中返回,所以基本上只需输入一次for循环并返回。此外,您正在创建新的字典,在每次迭代时都会覆盖moodDict。

def makemyDict(theFile):
    moodDict = {} # create the dictionary
    for i in theFile:
        (mood, name) = lines.split(",")
        moodDict['mood'] = name.strip() # strip off leading and trailing space
    return moodDict

顺便说一句,整个代码可以简化如下

def makemyDict(theFile):
    moodDict = {} # create the dictionary
    with open(theFile) as f:
        for line in f:
            (mood, name) = lines.split(",")
            moodDict['mood'] = name.strip() # strip off leading and trailing space
    return moodDict

d = makemyDict('mood.txt')
print(d)

答案 2 :(得分:0)

def bringFile():
    moodFile = open("mood.txt",'r')
    moodread = moodFile.readlines()
    moodFile.close()
    return moodread

def makemyDict(theFile):
    moodDict = {}
    for lines in theFile:
        mood, name = lines.split(",")

        moodDict[mood] = name

    return (moodDict)
        #print the dictionary

        # for m in moodDict:
        #     return(m, name)
        # print(lines)

def main():

    moodFile = bringFile()
    Dict = makemyDict(moodFile)
    print(Dict)

main()

答案 3 :(得分:0)

def line_gen(filename):
    with open(filename) as f:
        _ = (i.replace('\n', '').split(', ') for i in f)
        yield from _

m_dict = dict([*line_gen('mode.txt')])
print(m_dict)

出:

{'awkward': 'Mason Tyme', 'excited': 'Logan', 'sad': 'Jonathan Bower', 'mad': 'Penny', 'happy': 'Jennifer Clause'}
相关问题