Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - 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 is trivial.In my code when i run it, i get {}.

Im not sure if a for loop or if statement is needed.

 def build_book_dict(titles, pages, firsts, lasts, locations):
        if True:
            return dict()
        else: 
            None

    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)




result should be -->
 {'Fear and Lothing in Las Vegas': {'Publisher': {'Location': 'Aspen'},
 'Author': {'Last': 'Thompson', 'First': 'Hunter'}, 'Pages': 350},
 'Harry Potter': {'Publisher': {'Location': 'NYC'},
 'Author': {'Last': 'Rowling', 'First': 'J.K.'}, 'Pages': 200}}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

def build_book_dict(titles, pages, firsts, lasts, locations):
    dict = {}
    try:
        for i in range(len(titles)):
            dict[titles[i]] = {'Publisher':{'Location':locations[i]},
                               'Author':{'Last':lasts[i], 'First':firsts[i]}}
        return dict
    except 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...