繁体   English   中英

你如何通过函数返回字典?

[英]How do you return a dictionary through a function?

我试图通过使用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}}

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

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)

字典不会自动组装并知道您想要的格式。 由于您从一个独立的列表开始,您可以将它们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'}}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM