如何通过函数返回字典?

2024-09-28 01:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过代码中所示的函数使用jupyter笔记本返回字典。我是Python的初学者,不知道该怎么做,但我觉得答案很简单

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

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

Tags: andinbuildpagesdictlaslocationsbook
2条回答

字典不会自动组装自己并知道您想要的格式。由于您是从一个独立的列表开始的,因此您可以^{}将它们分组,以便轻松地对它们进行迭代并构建字典:

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

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

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)

相关问题 更多 >

    热门问题