Home > OS >  how do i match if value match my dictionary in python
how do i match if value match my dictionary in python

Time:06-29

I'm super new to python so i don't know anything even the basics of basics function so could anyone tell me how do i match value to my dictionary and where did i do wrong

#dictionary
id = {"2":"30", "3":"40"}

#json display from web
messages: {"id":2,"class":0,"type":1,"member":"N"}

if messages['id'] == id:  # << this part i think i'm doing it wrong too because it prints error`
    print ('the new id value from dictionary')  # << what do i put in here`
else:
    print ('error')

CodePudding user response:

Use if str(messages['id']) in id instead of if messages['id'] == id

CodePudding user response:

You need to convert the value to check to string in order to perform a valid comparison. Also, you should not use Python keywords as name variables to avoid additional issues:

id_dict = {"2":"30", "3":"40"}

#Use = to assign variables, not :
messages = {"id":2,"class":0,"type":1,"member":"N"}

if str(messages['id']) in id_dict:
    print ('the new id value from dictionary') 
else:
    print ('error')

Output:

the new id value from dictionary

CodePudding user response:

to check if a values is a key in a dict you can do it like this:

if messages['id'] in id:

but it will not work right away in your case. The values in the json data are integers so you need to convert them to match the dict. you will end up with this

if str(messages['id']) in id:

full code:

id = {"2": "30", "3": "40"}
messages = {"id":2,"class":0,"type":1,"member":"N"}
if str(messages['id']) in id:
    print(id[str(messages['id'])])
else:
    id[str(messages['id'])] = '50'

CodePudding user response:

The error occurs because you need to use an = to assign variables:

messages = {"id":2,"class":0,"type":1,"member":"N"}

instead of

messages: {"id":2,"class":0,"type":1,"member":"N"}

Concerning what you want to achieve, you are trying to access a dictionary value by using a default value ("error") in case the key doesn't exist. You can use dict.get for that, rather than if-else:

#dictionary
id_dict = {"2":"30", "3":"40"}

#json display from web
messages = {"id":2,"class":0,"type":1,"member":"N"}
    
print(id_dict.get(messages['id'], "error"))

Caveats:

  • Don't use id as a variable name, as it is a Python built-in keyword.
  • If the id_dict has string keys, you also need to use strings to access it, i.e. messages = {"id":2 ... will not give you the value "30" for id_dict = {"2":"30", "3":"40"}.
  • Related