Reputation: 1011
so lets say I have two lists, one with the names of directors and the other with the name of movies.
So:
directors = ['Tarr', 'Lynch' 'Coen']
movies = ['movie1', 'movie2', 'movie3', 'movie4']
End result I want:
{'movie1':'Tarr', 'movie2':'Tarr', 'movie3':'Lynch', 'movie4':'Tarr'}
But wait a minute? What about Coen? The other thing I want is that the value (director) to be randomly selected.
The part I'm really having trouble with is forcing the dictionary to show 4 elements. Python is only giving me 3 since the directors
list only contains 3 directors even though there are 4 movies.
Thanks guys.
Upvotes: 0
Views: 485
Reputation: 6777
Try this:
from random import choice
results = {}
for movie in movies:
results[movie] = choice(directors)
This will choose a random director for each movie in the movies list, and store them in a results dictionary.
You could do the same thing with a dictionary comprehension:
from random import choice
results = {x: choice(directors) for x in movies}
Upvotes: 4
Reputation: 9994
To make Ben's answer even more pythonic, use a dictionary comprehension (available in Python ≥ 2.7):
import random
directors = ['Tarr', 'Lynch' 'Coen']
movies = ['movie1', 'movie2', 'movie3', 'movie4']
results = { movie : random.choice(directors) for movie in movies }
(I like to simply import random
instead of from random import choice
, so I can refer to random.choice
by its fully qualified name and thus get code that's telling the reader that it's performing a random choice.)
Upvotes: 2
Reputation: 311
You might want to tell us if you are choosing with replacement or not. Anyway I hope this helps (this is with replacement):
import random
directors = ['Tarr', 'Lynch' 'Coen']
movies = ['movie1', 'movie2', 'movie3', 'movie4']
my_dictionary = {}
for each_movie in movies:
my_dictionary[each_movie] = random.choice(directors)
print my_dictionary
Upvotes: 2