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

时间:2020-05-08 11:42:29

标签: python json dictionary

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

在此示例中,该程序应删除player1和player2的全部,因为我想删除键稀有性中带有字符串“ rare”的所有玩家。

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

2 个答案:

答案 0 :(得分:2)

您可以使用 dict理解来完成它:

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)

答案 1 :(得分:0)

尝试一下。

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

for player in data:
    if player['rarity'] in ['rare', 'super_rare']:
        rare_players.append(player)

print(rare_players)
相关问题