2016-12-15 55 views
0

建立字典我想在python中使用open函数建立一个字典。 每行中的第一个单词将是该集合的关键字,该行中由','分隔的每个其他单词都将是一个值。如何从文本文件python 2.7

例如:

movies_file = open("movies.txt", "r") 
for line in movies_file: 
    # here I want to create the list 

在每一行有演员的名字后,他在第一线发挥,例如电影:

布拉德·皮特,海洋十一点,特洛伊

我需要创建一个列表或一组,其中的每一行 关键是演员的名字和值是电影。 这样的东西:

Brad Pitt["ocean eleven",troy"] 
Antony Hopkins["hanibal",....]

等等的每一行。

+0

格式化您的问题 –

回答

0

您可以简单地使用split函数来分隔每一行。这将返回一个字符串列表,您可以使用slice将名称与影片分开。 然后,剩下的就是将这些插入到字典中:

dictionary = {} 

with open("movies.txt") as movies_file: 
    for line in movies_file: 
     tokens = line.strip().split(",") # Split line into tokens 
     name = tokens[0]     # First token of line 
     movies = tokens[1:]    # Remaining tokens 
     dictionary[name] = movies 

print dictionary