Function to create nested dictionary from lists [closed]

2024/11/16 3:35:17

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 book is its title The value associated with that key is a dictionary

In that dictionary there will be Three keys: They are all strings, they are: "Pages", "Author", "Publisher"

"Pages" is associated with one value - an int "Author" is associated with a dictionary as value That "Author" dictionary has two keys: "First", and "Last" each with a string value "Publisher" is associated with a dictionary as value That "Publisher" dict has one key "Location" with a string as value.

An Example might look like:

{"Harry Potter": {"Pages":200, "Author":{"First":"J.K", "Last":"Rowling"}, "Publisher":{"Location":"NYC"}},
"Fear and Lothing in Las Vegas": { ...}}

Code a function called "build_book_dict" ACCEPT five inputs, all lists of n-length A list of titles, pages, first, last, and location.

RETURN a dictionary as described above. Keys must be spelled just as they appear above - correctly and capitalized.


Here is an example:

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)

{'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}}

My code currently looks the following:

def build_book_dict(titles, pages, firsts, lasts, locations):inputs = zip(titles, pages, firsts, lasts, locations)for titles, pages, firsts, lasts, locations in inputs:dict = {titles : {"Pages" : pages,"Author" : {"First" : first,"Last" : last},"Publisher" : {"Location" : locations},},}return dict

But it only stores the information of the last "book".

Answer

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.

https://en.xdnf.cn/q/118978.html

Related Q&A

Pygame not using specified font

So I am having a problem in pygame where I specify the font and size to use, but when my program is run, the font and size are the default.Here is where I define the textdef font(self):*****FATAL - THI…

port management in python/flask application

I am writing a REST API using the micro framework Flask with python programming language. In the debug mode the application detect any change in source code and restart itself using the same host and p…

using def with tkinter to make simple wikipedia app in python

I am beginner in python. I am trying to make a python wiki app that gives you a summary of anything that you search for. My code is below:import wikipediaquestion = input("Question: ")wikiped…

Only length-1 arrays can be converted to Python scalars with log

from numpy import * from pylab import * from scipy import * from scipy.signal import * from scipy.stats import * testimg = imread(path) hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0] hist…

Deploying Django with apache using wsgi.py

Im trying to deploy a Django project on a linode server that has apache, some other django projects and a php project on it. Also my project is in a virualenv and the other django projects arent.My Dja…

Building a decision tree using user inputs for ordering goods

I am trying to program a decision tree to allow customers to order goods based on their input. So far, I have devised a nested if-elif conditional structure to decide if customer want to order what or…

How to de-serialize the spark data frame into another data frame [duplicate]

This question already has answers here:Explode array data into rows in spark [duplicate](3 answers)Closed 4 years ago.I am trying to de-serialize the the spark data frame into another data frame as exp…

How to pull specific key from this nested dictionary?

{"newData": [{"env1": [{"sins": [{"host": "test.com","deployTime": "2015-07-23 11:54 AM",…}],"name": “hello”}, {"…

Dropping cell if it is NaN in a Dataframe in python

I have a dataframe like this.Project 4 Project1 Project2 Project3 0 NaN laptio AB NaN 1 NaN windows ten NaN 0 one NaN NaN 1 …

How can I iterate through excel files sheets and insert formula in Python?

I get this error TypeError: Workbook object is not subscriptablewhen i run this code import xlsxwriter from openpyxl import load_workbookin_folder = rxxx #Input folder out_folder = rxxx #Output folde…