ShadyBears
ShadyBears

Reputation: 4185

Dictionary with python

def make_scores_dict(names, scores):
    for i in range(len(names)):
        scores_dict[names[i]] = scores[i]

    return scores_dict



names=['Joe', 'Tom', 'Bob', 'Emily', 'Sue']
scores=[10, 23, 13, 18, 12]

dict = make_scores_dict(names, scores)

print #How do I print out a specific name? This is where I'm stuck at

Essentially I need to take 2 lists and make a dictionary with keys/values. I'm stuck on how to print out the specified name. For example, if I want to print out Emily and her value how would I do that?

Upvotes: 2

Views: 443

Answers (2)

icktoofay
icktoofay

Reputation: 129119

Once you've made a dict mapping names to scores, you can use []:

>>> print scores['Emily']
18

Note that I've renamed dict to scoresdict is the name of the dictionary type, and it's best to not overwrite it. Once you've changed that, there's a much more concise way to create the dictionary:

>>> scores = dict(zip(names, scores))

zip combines any number of iterables pairwise, e.g.:

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]

It just happens that dict can take a list of tuples in this format to create a dictionary:

>>> dict([('one', 1), ('two', 2)])
{'one': 1, 'two': 2}

Upvotes: 2

karthikr
karthikr

Reputation: 99670

You can just do

def make_scores_dict(names, scores):
    return dict(zip(names, scores))

To fix what you were trying to do:

def make_scores_dict(names, scores):
    scores_dict = {}
    for i in range(len(names)):
        scores_dict[names[i]] = scores[i]

    return scores_dict

OR

def make_scores_dict(names, scores):
    scores_dict = {}
    for i, name in enumerate(names):
        scores_dict.update({name: scores[i]})
    return scores_dict

Upvotes: 3

Related Questions