gpt4 book ai didi

python - 如果键包含字符串,则删除整个 json 对象

转载 作者:行者123 更新时间:2023-12-04 10:04:05 25 4
gpt4 key购买 nike

如果对象的键包含字符串,我该如何删除整个对象?

在这个例子中,程序应该删除整个 player1 和 player2,因为我想删除 key rarity 中带有字符串“rare”的所有玩家。

{
"player": {
"rating": "99",
"rarity": "super_rare"
},
"player2": {
"rating": "87",
"rarity": "rare"
},
"player3": {
"rating": "89",
"rarity": "common"
}
}

最佳答案

你可以使用字典理解来做到这一点:

data = {
"player": {
"rating": "99",
"rarity": "super_rare"
},
"player2": {
"rating": "87",
"rarity": "rare"
},
"player3": {
"rating": "89",
"rarity": "common"
}
}

filtered_data = {k: v for k, v in data.items() if "rare" not in v["rarity"]}
print(filtered_data) # {'player3': {'rating': '89', 'rarity': 'common'}}

编辑:

如果你想从文件读取/写入数据,尝试:

import json

file_name = "full/path/to/file"

# read the data
with open(file_name, "r") as fr:
data = json.load(fr)

# manipulate the data
filtered_data = {k: v for k, v in data.items() if "rare" not in v["rarity"]}

# write the data back to file
with open(file_name, "w") as fw:
json.dump(filtered_data, fw)

关于python - 如果键包含字符串,则删除整个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61678373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com