-1

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()
  • Do you mean dict value or dict key? – Ted Brownlow Jan 10 '21 at 18:13
  • why would you use a list? as value of user_data['users'] ? – Dieter Jan 10 '21 at 18:14
  • Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – mkrieger1 Jan 10 '21 at 18:14
  • @Dieter so I could append data to it – João Brito Jan 10 '21 at 18:22
  • @mkrieger had seen that one before posting it didn't work though – João Brito Jan 10 '21 at 18:25
  • @JoãoBrito - a dictionary is an unordered key - values list, whereby the keys has to be unique. ( maybe a good practice --> give each user an ID instead of using a real (string) name). + yes you can add new values to a dictionary --> user_data['users'][username] = { ... } <--- – Dieter Jan 10 '21 at 19:18

1 Answers1

0

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'])
kwkt
  • 1,058
  • 3
  • 10
  • 19