Remove entire json object if key contains string

Viewed 563

How do I remove the entire object if it has a key that contains a string?

In this example the program should remove the entirety of player1 and player2 because I want to remove all players with the string "rare" in the key rarity.

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

You can do it using dict comprehension:

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'}}

Edit:

If you want to read/write the data from/to file, try:

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)

Try this.

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)
Related