Summary of two methods for python dictionary values

  • 2020-12-05 17:16:26
  • OfStack

As shown below:


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

There are two ways to get the value of name


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

It was found that the two results were identical without any difference.

So how do you choose these two different dictionary values?

If the dictionary is known, we can pick any one, and when we're not sure if there's a key in the dictionary, the way I did it is this


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

Because using a[' age'] directly without first judging will result in an error of keyerror, indicating that there is no value for this key.

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


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

To change the value of value, you need to pass


a[ ' name']='Jack'

Use a. get(' name') = 'Jack'

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


Related articles: