从文件的每一行制作一个字典 [英] Making a dictionary from each line in a file

查看:95
本文介绍了从文件的每一行制作一个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从该文件中创建字典:密钥是第一个单词,之后的值是所有单词.

I am trying to make a dictionary from this file: with the key being the first word, and the values being all words afterwards.

andrew fred
fred
judy andrew fred
george judy andrew
john george

这是我的代码:

follows_file = open("C:\\Users\\Desktop\\Python\\follows.txt")
followers = {}
for line in follows_file:   #==> [Judy Andrew Fred]
    users = line.split(' ')     #==> [Judy, andrew, Fred, ....]
    follower = users[0]     #==> [Judy]
    followed_by = users[1:] #==> [Andrew, Fred]

    for user in followed_by:
        # Add the 'follower to the list of followers user
        if user not in followers:
            followers[user] = []
        followers[user].append(follower)
print(followers.items())

当我打印 follower 跟着变量时,它们是正确的,但是我很难将它们正确地添加到字典中.这就是输出

When I print the follower and followed by variable, they are correct, but i'm having trouble adding them into the dictionary correctly; with this being the output

dict_items([('fred\n', ['andrew', 'judy']), ('andrew', ['judy']), ('judy' ['george']), ('andrew\n', ['george']), ('george', ['john'])])

我想要的输出将是

(Andrew[Fred])(Fred[])(judy[Andrew Fred])(George[Judy Fred])(john[george])

非常感谢您的协助!

推荐答案

编辑的答案由于@ PM2Ring和@IljaEverilä的评论而得到了改进.

这是我使用字典理解的原始解决方案

Here is my original solution using a dictionary comprehension

followers = {line.split()[0]: line.split()[1:] for line in follows_file}

@IljaEverilä提出的一种更有效的替代方法是避免两次调用split

A more efficient alternative proposed by @IljaEverilä, which avoids calling split twice, is:

followers = {follower: followees for follower, *followees in map(str.split, follows_file)}

结果:

{'andrew': ['fred'],
 'fred': [],
 'george': ['judy', 'andrew'],
 'john': ['george'],
 'judy': ['andrew', 'fred']}

请注意,以上两种解决方案均假定您的文件不包含重复的密钥.

Note that both of the above solutions assume that your file contains no duplicate keys.

别忘了之后关闭文件:

follows_file.close()

或者更好,只需使用上下文管理器即可为您处理文件关闭:

Or better, just use a context manager, which handles the file closing for you:

with open('C:\\Users\\zacan\\Desktop\\Python\\follows.txt', 'r') as follows_file:
    followers = {follower: followees for follower, *followees in map(str.split, follows_file)}

这篇关于从文件的每一行制作一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆