创建一个从2-D列表词典创建一个、词典、列表

由网友(多余的解释)分享简介:我需要创建一个字典,以笔者为重点,并在手,价量,这本书的名字作为值的姓氏和名字。 I need to create a dictionary, with the last and first name of the author as the key, and the quantity on hand, price,...

我需要创建一个字典,以笔者为重点,并在手,价量,这本书的名字作为值的姓氏和名字。

I need to create a dictionary, with the last and first name of the author as the key, and the quantity on hand, price, and the book's name as the values.

[['Shakespeare', 'William', 'Rome And Juliet', '5', '5.99'], ['Shakespeare', 'William', 'Macbeth', '3', '7.99'], ['Dickens', 'Charles', 'Hard Times', '7', '27.00'], ['']]

我编译这个2-D名单,到目前为止,我卡住了。

I've compiled this 2-D list, so far and I'm stuck.

任何帮助将是AP preciated!

Any help would be appreciated!

推荐答案

下面将创建一个每个作者的名称映射到列表的书,他们已经写字典。使用名为 defaultdict 这在集合定义模块。

The following will create a dictionary that maps each author's name to alistof books they've written. This is done using a specialization of the built-in dictionary type nameddefaultdictwhich is defined in thecollectionsmodule.

from collections import defaultdict
from pprint import pprint

books = [['Shakespeare', 'William', 'Rome And Juliet', '5', '5.99'],
         ['Shakespeare', 'William', 'Macbeth', '3', '7.99'],
         ['Dickens', 'Charles', 'Hard Times', '7', '27.00'],
         ['']]

d = defaultdict(list)
for book in (book for book in books if book[0]):
    d[book[0], book[1]].append(book[2:])

pprint(d)

输出:

{('Dickens', 'Charles'): [['Hard Times', '7', '27.00']],
 ('Shakespeare', 'William'): [['Rome And Juliet', '5', '5.99'],
                              ['Macbeth', '3', '7.99']]}
阅读全文

相关推荐

最新文章