我需要过滤这个字典(书-1,书-2和书-3)中的所有键,这些键可以共享字符串“book”,并保存在一个新的字典中。在这个例子中,我不需要下载‘自行车’。
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])发布于 2022-05-10 15:35:03
这可以通过dict理解来实现,可以根据所需的过滤器进行更新:
new_dict = {key: value for key, value in info['store'].items() if "book" in key}https://stackoverflow.com/questions/72188986
复制相似问题