如何仅提取一个值的值以及字典中的键?

How can I extract the value of only one value along with the key in a dictionary?

例如,

books={1001:['Inferno','Dan Brown','Anchor Books','Thriller',42.00,70],
       1002:['As You Like It','William Shakespear','Penguin Publications','Classics',20.00,54],
       1003:['The Kite Runner','Khaled Hosseini','Bloomsbury Publcations','Fiction',30.00,70],
       1004:['A Thousand Splendid Suns','Khaled Hosseini','Bloomsbury Publications','Fiction',35.00,70],
       1005:['The Girl on The Train','Paula Hawkins','Riverhead Books','Fiction',28.00,100],
       1006:['The Alchemist','Paulo Coelho','Rupa Books','Fiction',25.00,50]}

如何只显示密钥和书名?

如果你知道书名的索引,它总是在同一个地方。你可以这样做:

for key, book_data in books.items():
    print key, book_data[0]

如果你想要所有的钥匙和书名:

books={1001:['Inferno','Dan Brown','Anchor Books','Thriller',42.00,70],
       1002:['As You Like It','William Shakespear','Penguin Publications','Classics',20.00,54],
       1003:['The Kite Runner','Khaled Hosseini','Bloomsbury Publcations','Fiction',30.00,70],
       1004:['A Thousand Splendid Suns','Khaled Hosseini','Bloomsbury Publications','Fiction',35.00,70],
       1005:['The Girl on The Train','Paula Hawkins','Riverhead Books','Fiction',28.00,100],
       1006:['The Alchemist','Paulo Coelho','Rupa Books','Fiction',25.00,50]}

for key, (book_name, *book_info) in books.items():
    print(key, book_name)

输出:

1001 Inferno
1002 As You Like It
1003 The Kite Runner
1004 A Thousand Splendid Suns
1005 The Girl on The Train
1006 The Alchemist

解释:

这里*运算符用于元组打包或解包。例如:

>>> book = ['Inferno','Dan Brown','Anchor Books','Thriller',42.00,70]
>>> book_name, *book_info = book
>>> print(book_name)
Inferno
>>> print(book_info)
['Dan Brown', 'Anchor Books', 'Thriller', 42.0, 70]

所以这里列表的第一个元素被分配给book_name,然后使用*运算符将其余元素打包到book_info中。 因此,当您迭代 books.items 时,对于每次迭代,您都会获得键值对。对于第一次迭代,键值对将如下所示:

>>> pair = (1001, ['Inferno', 'Dan Brown', 'Anchor Books', 'Thriller', 42.0, 70])
# so,
>>> key, (book_name, *book_info) = (1001, ['Inferno', 'Dan Brown', 'Anchor Books', 'Thriller', 42.0, 70])
>>> print(key)
1001
>>> print(book_name)
Inferno
>>> print(book_info)
['Dan Brown', 'Anchor Books', 'Thriller', 42.0, 70]

元组中的第一个值分配给 key,元组中的第二个值(列表)分配给 (book_name, *book_info)

参考: PEP 3132 -- Extended Iterable Unpacking

否则,如果您有钥匙:

#say:
key = 1001
print(f'{key} : {books[key][0]}')

输出:

1001 : Inferno

解包示例

>>> book_ids, book_names = zip(*[(key, book_name) for key, (book_name, *_) in books.items()])
>>> book_ids
(1001, 1002, 1003, 1004, 1005, 1006)
>>> book_names
('Inferno',
 'As You Like It',
 'The Kite Runner',
 'A Thousand Splendid Suns',
 'The Girl on The Train',
 'The Alchemist')

只需访问相关的书键并获取值列表的第 0 个元素。

key = input("What is your book key?")
print (key, books[key][0])

一个班轮答案:

[print(key,books[key][0]) for key in books.keys()]