问题
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.
Any help would be appreciated!
回答1:
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 nameddefaultdictwhich 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)
Output:
{('Dickens', 'Charles'): [['Hard Times', '7', '27.00']],
('Shakespeare', 'William'): [['Rome And Juliet', '5', '5.99'],
['Macbeth', '3', '7.99']]}
回答2:
It doesn't sound like you have much experience with Python. You should note the following sections of the tutorial (as you make your way through the entire tutorial, which is well worth your time!): looping techniques, dictionaries, and tuples and sequences.
In the end, you will probably want something along these lines:
>>> 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']}
Note that dictionary keys must be immutable, so I made each key of d
a tuple.
来源:https://stackoverflow.com/questions/23449030/create-dictionary-from-2-d-list