2017-07-16 47 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()) 

基本上,我们在这里做的是我们正在制作一个列表,然后将列表设置为字典中的一个键。