2017-07-16 72 views
1

我試圖在創建字典後將值添加到密鑰。將值添加到基於不同長度的密鑰

這是我到目前爲止有:

movie_list = "movies.txt" # using a file that contains this order on first line: Title, year, genre, director, actor 
in_file = open(movie_list, 'r') 
in_file.readline() 

def list_maker(in_file): 
    movie1 = str(input("Enter in a movie: ")) 
    movie2 = str(input("Enter in another movie: ")) 

    d = {} 
    for line in in_file: 
     l = line.split(",") 
     title_year = (l[0], l[1]) # only then making the tuple ('Title', 'year') 
     for i in range(4, len(l)): 
      d = {title_year: l[i]} 

     if movie1 or movie2 == l[0]: 
      print(d.values()) 

輸出我明白了:

Enter in a movie: 13 B 
Enter in another movie: 1920 
{('13 B', '(2009)'): 'R. Madhavan'} 
{('13 B', '(2009)'): 'Neetu Chandra'} 
{('13 B', '(2009)'): 'Poonam Dhillon\n'} 
{('1920', '(2008)'): 'Rajneesh Duggal'} 
{('1920', '(2008)'): 'Adah Sharma'} 
{('1920', '(2008)'): 'Anjori Alagh\n'} 
{('1942 A Love Story', '(1994)'): 'Anil Kapoor'} 
{('1942 A Love Story', '(1994)'): 'Manisha Koirala'} 
{('1942 A Love Story', '(1994)'): 'Jackie Shroff\n'} 
.... so on and so forth. I get the whole list of movies. 

我怎麼會去這樣做,如果我想在這兩個電影進入(任2個電影作爲鍵值(電影1,電影2)的聯合)?

例子:

{('13 B', '(2009)'): 'R. Madhavan', 'Neetu Chandra', 'Poonam Dhillon'} 
{('1920', '(2008)'): 'Rajneesh Duggal', 'Adah Sharma', 'Anjori Alagh'} 

回答

0

如果對不起輸出不完全你想要什麼,但這裏是你應該怎麼做:

d = {} 
for line in in_file: 
    l = line.split(",") 
    title_year = (l[0], l[1]) 
    people = [] 
    for i in range(4, len(l)): 
     people.append(l[i]) # we append items to the list... 
    d = {title_year: people} # ...and then make the dict so that the list is in it. 

    if movie1 or movie2 == l[0]: 
     print(d.values()) 

基本上,我們在這裏做的是我們正在製作一個列表,然後將列表設置爲字典中的一個鍵。