Search code examples
pythonjsondictionarykey-value-store

Check if python dict value exists


So I'm new to dicts and I'm trying to lookup and save usernames inside a json dictionary and I keep getting that the username is not in the dictionary, I've tried a few solutions I found here but none seem to work, is it something with my dict?

        username = input("Write your username: ")

            user_data['users'].append({
                'name': f'{username}',
                'highscore': '0',
                'table': ['-', '-', '-', '-', '-', '-', '-', '-', '-'],
                'turn': '1'
            })
            with open('user_data.json', 'w') as file:
                json.dump(user_data, file, indent=4)

Tried this and a few similar ones

"name" in user_data.values()

Solution

  • You need to look for name key in each of the dictionaries in the list that corresponds to the key users of the dictionary user_data (that was a mouthful).

    any('name_to_search_for' == user['name'] for user in user_data['users'])