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:
- How to Fix Errors encountered in executing Python scripts with command line parameters
- How to Fix “HTTP error 403: forbidden” in Python 3. X
- KeyError: b ‘TEST’ problem in python3 conversion from csn-rcnn code
- How to Fix Python reading large local file memory error
- Python quote error: * * * keyerror: u ‘\ uxx’ [How to Solve]
- An introduction to sys modules in Python and how packages are imported and used
- Python Pandas Error: KeyError: 0 [How to Solve]
- How to Solve Automatic error keyerror:***‘
- [Solved] raise KeyError(key) from err KeyError: ‘Dates‘
- Python: How to Solve multiprocessing module Error in Windows
- How to Solve Python WARNING: Ignoring invalid distribution -ip (e:\python\python_dowmload\lib\site-packages)
- Python: How to Delete Empty Files or Folders in the Directory
- Python: How to Reshape the data in Pandas DataFrame
- How to Fix tensorflow2.0 tf.placeholder Error
- Error in sitecustomize set PYTHONVERBOSE for traceback KeyError: ‘PYTHONPATH’
- Python: How to Solve mysqlclient Install Error in Mac
- How does Python output colored fonts in the CMD command line window
- How to Solve Python AttributeError: ‘dict’ object has no attribute ‘item’
- Pychar: How to Fix using SQLite to report an error: java.lang.ClassNotFoundException
- Python: How to parses HTML, extracts data, and generates word documents