如何通过函数返回字典?

时间:2019-05-27 22:44:09

标签: python jupyter-notebook

我正在尝试使用jupyter笔记本通过代码中显示的函数返回字典。我是Python的初学者,不确定如何解决此问题,但是我觉得答案很简单。在我运行它的代码中,我得到{}。

不确定是否需要for循环或if语句。

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

2 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案:
注意!所有列表的大小必须相同!

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)

答案 1 :(得分:0)

字典不会自动组装并知道您想要的格式。由于您是从一个独立的列表开始的,因此可以zip将它们分成几组,以轻松地遍历它们并构建您的字典:

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)

结果

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