将内容归档到字典中

时间:2016-12-15 09:32:42

标签: python file dictionary

我需要将此文件内容转换为字典,以便dict中的每个键都是电影的名称,每个值都是在集合中播放的actor的名称。

文件内容示例:

Brad Pitt, Sleepers, Troy, Meet Joe Black, Oceans Eleven, Seven, Mr & Mrs Smith
Tom Hanks, You have got mail, Apollo 13, Sleepless in Seattle, Catch Me If You Can
Meg Ryan, You have got mail, Sleepless in Seattle
Diane Kruger, Troy, National Treasure
Dustin Hoffman, Sleepers, The Lost City
Anthony Hopkins, Hannibal, The Edge, Meet Joe Black, Proof

2 个答案:

答案 0 :(得分:1)

这应该让你开始:

line = "a, b, c, d"
result = {}
names = line.split(", ")
actor = names[0]
movies = names[1:]
result[actor] = movies

答案 1 :(得分:0)

尝试以下方法:

res_dict = {}

with open('my_file.txt', 'r') as f:
    for line in f:
        my_list = [item.strip() for item in line.split(',')]
        res_dict[my_list[0]] = my_list[1:]  # To make it a set, use: set(my_list[1:])

<强>解释

split()用于使用,分隔符

拆分每一行以形成列表

strip()用于删除上一个列表中每个元素周围的空格

使用with statement时,您无需明确关闭文件。

[item.strip() for item in line.split(',')]被称为list comprehension

<强>输出:

>>> res_dict
{'Diane Kruger': ['Troy', 'National Treasure'], 'Brad Pitt': ['Sleepers', 'Troy', 'Meet Joe Black', 'Oceans Eleven', 'Seven', 'Mr & Mrs Smith'], 'Meg Ryan': ['You have got mail', 'Sleepless in Seattle'], 'Tom Hanks': ['You have got mail', 'Apollo 13', 'Sleepless in Seattle', 'Catch Me If You Can'], 'Dustin Hoffman': ['Sleepers', 'The Lost City'], 'Anthony Hopkins': ['Hannibal', 'The Edge', 'Meet Joe Black', 'Proof']}