创建一个从2-D列表词典 [英] Create dictionary from 2-D list

查看:150
本文介绍了创建一个从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, 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!

推荐答案

下面将创建一个每个作者的名称映射到列表的书,他们已经写字典。使用名为 <$ c中的内置词典类型的专业化这是通过$ C> 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']]}

这篇关于创建一个从2-D列表词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆