The paper contains 2254 words and is expected to last 7 minutes

Source: Pexels


Dictionaries are indispensable helpers in the age of enlightenment

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


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

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

· Unlike lists, these terms have no clear order.


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


author = {Copy the code
"first_name":"Jonathan".Copy the code
"last_name":"Hsu".Copy the code
"username":"jhsu98"Copy the code
}Copy the code

Old (bad) way to access dictionary values


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


author = {Copy the code
"first_name":"Jonathan".Copy the code
"last_name":"Hsu".Copy the code
"username":"jhsu98"Copy the code
}print(author['username']) # jhsu98Copy the code
print(author['middle_initial']) # KeyError: 'middle_initial'Copy the code

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


Although we can wrap our statements in try/except or if statements, it is more appropriate to stack dictionary terms.


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

If you have a JavaScript background, it might be tempting to refer to dictionary values with dot notation. This does not work in Python.


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

Use the.get() method


Source: Pexels


The safest way to access dictionary values is to use the.get() method. This function takes two arguments:


· First (required): Name of term to be retrieved. Can be strings or variables, allowing dynamic retrieval of terms.

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


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

If the term has been published before,.get() works no differently than a traditional square bracket reference. 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 Python equivalent of null is None.


Use the.setdefault() method


Sometimes, not only do you want to avoid undefined terms in the dictionary, but you also want your code to automatically correct its data structure. .setdefault() has the same structure as.get(). However, when the term is not defined, in addition to returning the default value, the dictionary term will also be set to that value.


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

As you can see from the example above,.setdefault() is the same as square bracket notation or.get() in the presence of the term. Not only that, it returns the passed default, as does.get(), when the term does not exist.


It differs from.get() in that its terms and definitions are now part of the dictionary, as shown below.


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

.get() and.setdefault() are excellent techniques for referencing dictionary values…… It just takes some time to break out of old habits and adopt the practice.


Source: Pexels


If you don’t want to modify the raw data,.get() is your best option.


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

Leave a comment like follow

We share the dry goods of AI learning and development. Welcome to pay attention to the “core reading technology” of AI vertical we-media on the whole platform.



(Add wechat: DXSXBB, join readers’ circle and discuss the freshest artificial intelligence technology.)