2016-12-15 161 views
-2

我需要將此文件內容轉換爲字典,以便字典中的每個鍵都是電影的名稱,每個值都是在其中播放的演員的名稱。文件內容將文件內容轉換爲字典

例子:

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 

回答

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']} 
+0

我可以理解爲什麼downvote? – ettanany

+0

一些SO用戶認爲不應該回答沒有顯示任何研究成果的問題。 – vaultah

+0

對不起@vaultah,但是當我們看到像「我什至不知道從哪裏開始」這樣的東西時,我認爲我們應該幫助! – ettanany

1

這應該讓你開始:

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