从二维列表创建字典

时间:2014-05-03 19:44:44

标签: python python-3.x dictionary 2d

我需要创建一个字典,其中作者的姓氏和名字作为关键字,手头的数量,价格和图书的名称作为值。

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

我已经编制了这个2-D列表,到目前为止我已经卡住了。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

听起来你对Python有很多经验。您应该注意本教程的以下部分(当您完成整个教程时,这非常值得您花时间!):looping techniquesdictionariestuples and sequences

最后,您可能会想要这些内容:

>>> books = [['Shakespeare', 'William', 'Rome And Juliet', '5', '5.99'], ['Shakespeare', 'William', 'Macbeth', '3', '7.99'], ['Dickens', 'Charles', 'Hard Times', '7', '27.00'], ['']]
>>> d = dict()
>>> for book in books:
    if book and len(book) > 3:  # make sure book list is not empty and has more than three elements
        d[tuple(book[:2])] = book[3:] + [book[2]]  # make sure value reflects your desired order

>>> d
{('Dickens', 'Charles'): ['7', '27.00', 'Hard Times'], ('Shakespeare', 'William'): ['3', '7.99', 'Macbeth']}

请注意,字典键必须是不可变的,因此我将d的每个键都设为元组。

答案 1 :(得分:0)

以下内容将创建一个字典,将每位作者的姓名映射到他们已经写过的list本书。这是使用collections模块中定义的名为defaultdict的内置字典类型的专门化来完成的。

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