如何通过函数返回字典? [英] How do you return a dictionary through a function?

查看:182
本文介绍了如何通过函数返回字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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)

结果

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

这篇关于如何通过函数返回字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆