Skip to content Skip to sidebar Skip to footer

How Do You Return A Dictionary Through A Function?

I am trying to return a dictionary through a function shown in the code using jupyter notebooks. I am a beginner in Python and not sure how to go about this but I feel the answer i

Solution 1:

Here is a possible solution: Be careful! All the lists must be same size!

defbuild_book_dict(titles, pages, firsts, lasts, locations):
    dict = {}
    try:
        for i inrange(len(titles)):
            dict[titles[i]] = {'Publisher':{'Location':locations[i]},
                               'Author':{'Last':lasts[i], 'First':firsts[i]}}
        returndictexcept Exception as e:
        print('Invalid length', e)

titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
book_dict = build_book_dict(titles, pages, firsts, lasts, locations)
print (book_dict)

Solution 2:

The dictionary isn't going to automatically assemble itself and know the format you want. Since you are starting with a independent lists you can zip them into groups to easily iterate over them and build your dictionary:

defbuild_book_dict(*args):
    d = dict()
    for title, page, first, last, location inzip(*args):
        d[title] = {"Publisher": {"Location":location}, 
                    "Author": {"last": last, "first":first}, 
                    "Pages": page}
    return d

titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
book_dict = build_book_dict(titles, pages, firsts, lasts, locations)

from pprint import pprint # pretty print

pprint(book_dict)

Result

{'Fear and Lothing in Las Vegas': {'Author': {'first': 'Hunter',
                                              'last': 'Thompson'},
                                   'Pages': 350,
                                   'Publisher': {'Location': 'Aspen'}},
 'Harry Potter': {'Author': {'first': 'J.K.', 'last': 'Rowling'},
                  'Pages': 200,
                  'Publisher': {'Location': 'NYC'}}}

Post a Comment for "How Do You Return A Dictionary Through A Function?"