如何从字典中提取单个键值对?示例:仅显示书籍字典的键与书名
嘿,我来帮你搞定这两个字典处理的问题,都是Python里很常见的需求,咱们一步步来:
问题1:从字典中仅提取一个键及其对应的值
如果你已经明确知道要提取的具体键,最简单的方式就是直接通过键获取对应的值,然后把它封装成一个新字典即可。针对你给出的books字典,举个例子,假设你要提取键1001的条目:
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]} # 提取目标键及其值 target_key = 1001 extracted_item = {target_key: books[target_key]} print(extracted_item)
运行这段代码后,你会得到输出:{1001: ['Inferno', 'Dan Brown', 'Anchor Books', 'Thriller', 42.0, 70]}。
如果不确定目标键是否存在于字典中,为了避免抛出KeyError异常,建议先做个存在性检查,或者用get()方法:
target_key = 1007 # 一个不存在的键 extracted_item = {} # 方法1:先检查键是否存在 if target_key in books: extracted_item[target_key] = books[target_key] # 方法2:用get()方法,不存在则返回None book_details = books.get(target_key) if book_details is not None: extracted_item[target_key] = book_details
问题2:仅显示字典中的键与书籍名称
观察你的books字典结构,每个值都是一个列表,而列表的第一个元素就是书籍名称。基于这个特点,我们可以通过遍历字典的键值对,只保留需要的信息:
方式1:直接打印键和书名
如果只是想快速查看结果,直接遍历打印即可:
for book_id, book_details in books.items(): print(f"键:{book_id},书籍名称:{book_details[0]}")
运行后会逐行输出类似这样的内容:
键:1001,书籍名称:Inferno 键:1002,书籍名称:As You Like It ...
方式2:生成精简的新字典
如果需要把键和书名保存下来供后续使用,可以用字典推导式生成一个新的精简字典:
book_id_to_title = {book_id: book_details[0] for book_id, book_details in books.items()} print(book_id_to_title)
这段代码的输出会是:
{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'}
内容的提问来源于stack exchange,提问作者nix
相关产品推荐
相关产品推荐

