0

I'm trying to build a dictionary using the open function in python. The first word in each line will be the key of the set and every other word on that line separated by ',' will be a value.

For example:

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

In each line there is a name of the actor and after that the movies he played in, for example in the first line:

Brad Pitt,ocean eleven,troy

I need to create a list or set where for each line the key is the name of the actor and the values are the movies. something like:

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

and so on for each line.

Meyer
  • 1,662
  • 7
  • 21
  • 20

1 Answers1

0

You can simply use the split function to separate each line. This will return a list of strings, which you can slice to separate the name from the movies. Then, all that remains is to insert these into the dictionary:

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
Community
  • 1
  • 1
Meyer
  • 1,662
  • 7
  • 21
  • 20