首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >筛选包含Python中某些字符的Json键

筛选包含Python中某些字符的Json键
EN

Stack Overflow用户
提问于 2022-05-10 15:19:46
回答 1查看 869关注 0票数 0

我需要过滤这个字典(书-1,书-2和书-3)中的所有键,这些键可以共享字符串“book”,并保存在一个新的字典中。在这个例子中,我不需要下载‘自行车’。

代码语言:javascript
复制
import json

# some JSON file:
jInfo = '{"store":{"book-1":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"book-2":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"book-3":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"bicycle":{"color":"red","price":19.95}}}'

# parse jsonObject:
info = json.loads(jInfo)

# the result is a Python dictionary:
print(info["store"]["book-1"][0])
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-10 15:35:03

这可以通过dict理解来实现,可以根据所需的过滤器进行更新:

代码语言:javascript
复制
new_dict = {key: value for key, value in info['store'].items() if "book" in key}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72188986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档