SoFunction
Updated on 2024-12-11

A short summary of the two methods for fetching values in python dictionaries

As shown below:

a={'name':'tony','sex':'male'}

获得name的值的方式有两种

print a['name'],type(a['name'])
print ('name'),type(('name'))

The two results were found to be identical and there was no difference.

How do you choose between these two different ways of taking values from the dictionary?

If the dictionary is known, we can pick either one, and when we're not sure if a key exists in the dictionary, here's what I've done before

if 'age' in ():
 print a['age']

This is because using a['age'] directly without judging it first will result in a keyerror, indicating that there is no value for the key.

Instead, using ('age') does not generate an error, and the parser returns the value if it exists, or None if it does not.

if ('age'):
 print a['age'] 

To change the value of value, you need to pass the

a[‘name']='Jack'

Use('name') = 'Jack'

The compiler then prompts for the SyntaxError: can't assign to function call

Above this python dictionary in the two methods to take the value of the summary is all that I have shared with you, I hope to give you a reference, and I hope you support me more.