Instead of using square brackets to get dictionary values in Python, try this method

Dictionary is a good helper that can't be obtained in the period of enlightenment education

A dictionary is an unordered collection of terms and definitions, which means:

·Each data point has an identifier (i.e. term) and a value (i.e. definition).

·Terms must be unique in the dictionary and cannot be repeated.

·Unlike the list, these terms have no clear order.

Use braces to define dictionaries and commas to separate terms or definition pairs.

author = {
   "first_name":"Jonathan",
   "last_name":"Hsu",
   "username":"jhsu98"
}

Old (bad) methods of accessing dictionary values

The traditional way to access values in a dictionary is to use square bracket notation. This syntax embeds the names of terms in square brackets, as shown below.

author = {
   "first_name":"Jonathan",
   "last_name":"Hsu",
   "username":"jhsu98"
}print(author['username']) # jhsu98
print(author['middle_initial']) # KeyError: 'middle_initial'

Attempting to refer to a term that does not exist will result in KeyError. This can cause serious problems, especially when dealing with unpredictable business data.

Although our statements can be wrapped in try/except or if statements, they are more suitable for stacked dictionary terms.

author = {}try:
   print(author['username'])
except KeyError as e:
   print(e) # 'username'ifauthor['username']:
   print(author['username'])

If you have a JavaScript background, it may be attractive to refer to dictionary values with dots. This does not work in Python.

author = {
   "first_name":"Jonathan",
   "last_name":"Hsu",
   "username":"jhsu98"
}print(author.username)
# AttributeError: 'dict' object has no attribute 'username'

use. get() method

The safest way to access dictionary values is to use get() method. This function has two parameters:

·First (required): the name of the term to be retrieved. It can be a string or variable, allowing dynamic retrieval of terms.

·Second (optional): if the term does not exist, use the default value.

author = {
   "first_name":"Jonathan",
   "last_name":"Hsu",
   "username":"jhsu98"
}print(author.get('username')) # jhsu98
print(author.get('middle_initial', None)) # None

If the term has previously been published, then The way get() works is no different from traditional square bracket references. If no term is defined, a default value is returned so that exceptions do not have to be handled.

This default value can be any value, but remember that it is optional. If no default value is included, the equivalent of null value in Python is used.

use. setdefault() method

Sometimes, you not only want to avoid undefined terms in the dictionary, but also want the code to automatically correct its data structure The structure and of setdefault() Same as get(). However, when the term is undefined, in addition to returning the default value, the term of the dictionary will also be set to this value.

author = {
   "first_name":"Jonathan",
   "last_name":"Hsu",
   "username":"jhsu98"
}print(author.setdefault('username')) # jhsu98
print(author.setdefault('middle_initial', None)) # None

As can be seen from the above example, when the term exists setdefault() and square bracket notation or Same as get(). Moreover, when the term does not exist, it is associated with Return the default value passed like get().

It has nothing to do with get() differs in that its terms and definitions are now part of the dictionary, as shown below.

author = {
   "first_name":"Jonathan",
   "last_name":"Hsu",
   "username":"jhsu98"
}print(author.setdefault('middle_initial',None)) # None
print(author)
"""
{
  'first_name': 'Jonathan',
  'last_name': 'Hsu',
  'username': 'jhsu98',
  'middle_initial': None
}
""

. get() and setdefault() is an excellent technique when referring to dictionary values It just takes some time to break old habits and adopt this approach.

If you do not want to modify the original data get() is your only choice.

If you want to change the original data, use setdefault(), and you're done.

Added by tysonrileyreznor on Mon, 14 Feb 2022 04:50:54 +0200