Python dictionaries usually look for keys directly, for example
dict={'a':1,'b':2,'c':3}
print(dict['a'])
But if the key is not found, it will report: KeyError:
So you want to look at print(dict[‘d’])
Since the dict doesn’t have the key in it, it’s just going to report an error, and python gives us a great way to do that, which is to use
setdefault,The usage is as follows: dict.setdefault(key, [here set what you want the value to be if it doesn't exist, default is None]).
So here we can use this method to solve:
print(dict.setdefault('d',0))
If you want to add a new value to the dict, use setdefault. If you simply want to find the value, but the key does not exist, or you want to get a default value by reading the value through this key, then I recommend using defaultdict
I’ll start with this so-called Defaultdict from the Collections module, which is a collections module. Defaultdict (Function_factory) builds a Dictionary-like object where the value of the key is assigned by itself, but the type of value is an instance of a class in the Function_Factory and has a default value. Another concept introduced here is factory functions. Python’s factory functions are those built-in functions that are class objects, and when you call them, you’re actually creating an instance of a class. Int (), STR (),set(), etc.
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
d[k].append(v)
print(d['yellow'])
print(d['white'])
print(list(d.items()))
Our final output is as follows:
We can see that when d has no corresponding key, it returns an empty list, because the factory function we used when we set defaultdict is list, and the default value of list is empty list. Now let’s see what would happen if the factory function was set()
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(set)
for k, v in s:
d[k].add(v)
print(d['yellow'])
print(d['white'])
print(list(d.items()))
The output is as follows:
Read More:
- Python errors: valueerror: if using all scalar values, you must pass an index (four solutions)
- An introduction to sys modules in Python and how packages are imported and used
- Full explanation of SYS module of Python
- Python Pandas Typeerror: invalid type comparison
- pytorch RuntimeError: Error(s) in loading state_ Dict for dataparall… Import model error solution
- Python exports the gitlab project
- Python uses try… Except… To output detailed errors
- Python 3 urllib has no URLEncode attribute
- Python error collection: NameError: name ‘numpy’ is not defined
- ValueError: Found array with dim 4. Estimator expected and ValueError: Expected 2D array, got 1D array i
- python: File Processing and Input and Output
- Typeerror in Python regular expression: expected string or bytes like object
- Parallel processing in Python (Pool.map(), Pool.starmap(), Pool.apply ())
- How to Fix Errors encountered in executing Python scripts with command line parameters
- Pandas ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.an
- Python error: urllib.error.HTTPError : http Error 404: not found
- Python 3 uses the relative path import module
- Python: How to parses HTML, extracts data, and generates word documents
- KeyError: b ‘TEST’ problem in python3 conversion from csn-rcnn code
- Python classes that connect to the database