current position:Home>[Python] comparison of dictionary dict, defaultdict and orderdict
[Python] comparison of dictionary dict, defaultdict and orderdict
2022-02-01 05:41:44 【Hazelnut】
「 This is my participation 11 The fourth of the yuegengwen challenge 2 God , Check out the activity details :2021 One last more challenge 」
defaultdict
be located collections
In module .
Instantiate a defaultdict
When , You need to provide a callable object for the constructor , This callable object will be in __getitem__
It is called when it encounters a key that cannot be found , Give Way __getitem__
Return some default value . The callable object used to generate the default value is stored in a file named default_factory
In the instance properties of .
Take a chestnut
d = collections.defaultdict(list) # An empty dictionary
d['key'] # []
d.get('key') # None
Copy code
OrderedDict
be located collections
In module .
This type will keep the order when adding keys , So the order of key iterations is always the same .
OrderedDict
Of popitem
Method deletes and returns the last element in the dictionary by default , But if it's like my_odict.popitem(last=False)
Call it this way , Then it deletes and returns the first element added .
The abstract base class of dictionaries
collections.abc
There is Mapping
and MutableMapping
These two abstract base classes , Their function is to dict
And other similar types define formal interfaces .
The italics in the table are abstract methods / class .
Class name | Method / attribute | Parent class |
---|---|---|
Container | __contains__ | - |
Iterable | __iter__ | - |
Sized | __len__ | - |
Mapping | __getitem__ , __contains__ , __eq__ , __ne__ , get , items , keys, values | Container , Iterable , Sized |
MutableMappint | __setitem__ , __delitem__ , clear , pop , popitem , setdefault , update | Mapping |
dict
、defaultdict
、OrderDict
Method comparison
[]
Is an optional parameter .
Method / object | dict |
defaultdict |
OrderDict |
explain |
---|---|---|---|---|
d.clear() |
Yes | Yes | Yes | Remove all elements |
d.__contains__(k) |
Yes | Yes | Yes | Check k Is it included in d in |
d.copy() |
Yes | Yes | Yes | Latent reproduction |
d.__copy__() |
Yes | Used to support copy.copy |
||
d.default_factory |
Yes | stay __missing__ The function called in the function , Used to set values for elements that are not found |
||
d.__missing__(k) |
Yes | When __getitem__ When the method cannot find the corresponding key , Call the method |
||
d.__delitem__(k) |
Yes | Yes | Yes | Remove key as k The elements of |
d.fromkeys(it, [initial]) |
Yes | Yes | Yes | Put the iterator it Set the element in the map to the key in the map , If there is initial Parameters , Just take it as the value corresponding to these keys ( The default is None ) |
d.get(k, [default]) |
Yes | Yes | Yes | Return key k Corresponding value , No, k When to return to default or None |
d.__getitem__(k) |
Yes | Yes | Yes | Make the dictionary usable d[k] Return key in the form of k Corresponding value |
d.items() |
Yes | Yes | Yes | Returns all key value pairs |
d.__iter__() |
Yes | Yes | Yes | Get the iterator of the key |
d.keys() |
Yes | Yes | Yes | Back to all keys |
d.__len__() |
Yes | Yes | Yes | It can be used len(d) Form to get the number of dictionary key value pairs |
d.move_to_end(k, [last]) |
Yes | Set the key to k Move the element of the test to the front or back position (last The default is True ) |
||
d.pop(k, [default] |
Yes | Yes | Yes | Return key k Corresponding value , And remove the key value pair . No, k When to return to default or None |
d.popitem() |
Yes | Yes | Yes ( There are optional parameters last , The default is False , At this point, remove the earliest inserted key value pair , Otherwise, remove the last inserted key value pair ) |
Returns a random key value pair and removes it from the dictionary |
d.__reversed__() |
Yes | Iterators that return keys in reverse order | ||
d.setdefault(k, [default]) |
Yes | Yes | Yes | If there is a key in the dictionary k , Set its corresponding value to default , And then back to this value ; If there is no , Then let d[k] = default , Then return default |
d.__setitem__(k, v) |
Yes | Yes | Yes | Realization d[k] = v operation |
d.update(m, [**kargs]) |
Yes | Yes | Yes | m It can be a map or a key value pair iterator , Used to update d The corresponding entry in |
d.values() |
Yes | Yes | Yes | Returns all values in the dictionary |
copyright notice
author[Hazelnut],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010541416686.html
The sidebar is recommended
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
guess what you like
-
Daily python, Chapter 18, class
-
"I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
-
Django view
-
Python implements filtering emoticons in text
-
When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
-
Python crawler - get fund change information
-
Highlight actor using Python VTK
-
Python crawler actual combat: crawling southern weekend news articles
-
leetcode 406. Queue Reconstruction by Height(python)
-
leetcode 1043. Partition Array for Maximum Sum (python)
Random recommended
- Python * * packaging and unpacking details
- Python realizes weather query function
- Python from 0 to 1 (day 12) - Python data application 2 (STR function)
- Python from 0 to 1 (day 13) - Python data application 3
- Numpy common operations of Python data analysis series Chapter 8
- How to implement mockserver [Python version]
- Van * Python! Write an article and publish the script on multiple platforms
- Python data analysis - file reading
- Python data De duplication and missing value processing
- Python office automation - play with browser
- Python series tutorial 127 -- Reference vs copy
- Control flow in Python: break and continue
- Teach you how to extract tables in PDF with Python
- leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal(python)
- leetcode 1338. Reduce Array Size to The Half(python)
- Object oriented and exception handling in Python
- How to configure load balancing for Django service
- How to embed Python in go
- Python Matplotlib drawing graphics
- Python object-oriented programming 05: concluding summary of classes and objects
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values(python)
- leetcode 1433. Check If a String Can Break Another String(python)
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
- Python crawler series - network requests
- Python thread 01 understanding thread
- Analysis of earthquake distribution in the past 10 years with Python~
- You need to master these before learning Python crawlers
- After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
- Python uses redis
- Python crawler - ETF fund acquisition
- Detailed tutorial on Python operation Tencent object storage (COS)
- [Python] comparison of list, tuple, array and bidirectional queue methods
- Go Python 3 usage and pit Prevention Guide