问题
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}}
回答1:
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)
回答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:
def build_book_dict(*args):
d = dict()
for title, page, first, last, location in zip(*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'}}}
来源:https://stackoverflow.com/questions/56333154/how-do-you-return-a-dictionary-through-a-function