从二维列表创建字典 [英] Create dictionary from 2-D list
本文介绍了从二维列表创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建一个字典,以作者的姓氏和名字为关键字,以手头的数量、价格和书名作为值.
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'], ['']]
到目前为止,我已经编译了这个二维列表,但我被卡住了.
I've compiled this 2-D list, so far and I'm stuck.
任何帮助将不胜感激!
推荐答案
下面将创建一个字典,将每个作者的名字映射到他们所写书籍的list
.这是使用名为的内置字典类型的特化完成的defaultdict
在collections
模块中定义.
The following will create a dictionary that maps each author's name to alist
of books they've written. This is done using a specialization of the built-in dictionary type nameddefaultdict
which is defined in thecollections
module.
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']]}
这篇关于从二维列表创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文