Function To Create Nested Dictionary From Lists
I am tasked with the following question, but cannot come up with the right code: This exercise involves building a non-trivial dictionary.The subject is books. The key for each boo
Solution 1:
Use this function, the main change is that I add a d.update
:
def build_book_dict(titles, pages, firsts, lasts, locations):
inputs = zip(titles, pages, firsts, lasts, locations)
d = {}
for titles, pages, firsts, lasts, locations in inputs:
d.update({
titles : {
"Pages" : pages,
"Author" : {
"First" : firsts,
"Last" : lasts
},
"Publisher" : {
"Location" : locations
},
},
})
return d
And now:
print(build_book_dict(titles, pages, firsts, lasts, locations))
Becomes:
{'Harry Potter': {'Pages': 200, 'Author': {'First': 'J.K.', 'Last': 'Rowling'}, 'Publisher': {'Location': 'NYC'}}, 'Fear and Lothing in Las Vegas': {'Pages': 350, 'Author': {'First': 'Hunter', 'Last': 'Thompson'}, 'Publisher': {'Location': 'Aspen'}}}
Your code doesn't work because you're creating a new dictionary every time, not adding the dictionaries together, however d.update
overcomes this issue.
Additionally, I rename the variable dict
to d
, since dict
is a default keyword, whereas when you name a variable of dict
, you're not able to access the actual dict
keyword with that.
Solution 2:
Create the empty dict before the for loop. And then in the loop add to it like so:
defbuild_book_dict(titles, pages, firsts, lasts, locations):
inputs = zip(titles, pages, firsts, lasts, locations)
d = dict()
for titles, pages, firsts, lasts, locations in inputs:
d[titles] = {whatever}
return d
Solution 3:
You can use a dictionary comprehension:
titles = ["Harry Potter", "Fear and Lothing in Las Vegas"]
pages = [200, 350]
firsts = ["J.K.", "Hunter"]
lasts = ["Rowling", "Thompson"]
locations = ["NYC", "Aspen"]
data = {a:{'Pages':b, 'Author':{'First':c, 'Last':d}, 'Publisher': {'Location': e}} for a, b, c, d, e in zip(titles, pages, firsts, lasts, locations)}
Output:
{'Harry Potter': {'Pages': 200, 'Author': {'First': 'J.K.', 'Last': 'Rowling'}, 'Publisher': {'Location': 'NYC'}}, 'Fear and Lothing in Las Vegas': {'Pages': 350, 'Author': {'First': 'Hunter', 'Last': 'Thompson'}, 'Publisher': {'Location': 'Aspen'}}}
Post a Comment for "Function To Create Nested Dictionary From Lists"