python dict dictionary detailed description
The dictionary is implemented through the principle of hash table. Each element is a key-value pair. A unique hash value is calculated through the key of the element. This hash value determines the address of the element. Therefore, in order to ensure the address of the element No, it must be ensured that the key of each element and the corresponding hash value are completely different, and the key type must be unmodifiable, so the key type can be a numeric value, a string constant or a tuple, but it cannot be a list. Because the list can be modified.
So the dictionary has the following characteristics:
1. The query and insertion operations of elements are very fast, basically at a constant level
2. It takes up a large amount of memory, and uses Method of exchanging space for time
Dictionary initialization
The following methods are all equivalent
d={' a':1, 'b':2, 'c':3}
d=dict({'a':1, 'b':2, 'c':3})
d = dict([('a',1), ('b', 2), ('c', 3)])
d = dict(a=1, b=2 , c=3)
d = dict(zip(['a', 'b', 'c'], [1,2,3]))#This method can also be used to combine two Lists are merged into a dictionary
Assignment elements
1. e = d#Reference assignment, e and d are always the same
2. e = d.copy()# Value assignment, the two are not related
3. d.copy() is a shallow copy, when the value of the key-value pair encounters a dictionary or list , the dictionary or list will also change with the original change. At this time, the value is equivalent to the reference or pointer of the tuple or list, not itself. The tuple or list pointed to is actually the original one. This can be avoided by using the deepcopy() method of the copy module.
import copy dict1 = {'a': [1, 2], 'b': 3} dict2 = dict1 dict3 = dict1.copy() dict4 = copy.deepcopy(dict1) dict1['b'] = 'change'dict1['a'].append('change')print dict1 # {'a': [1, 2, 'change'], 'b': 'change'}print dict2 # {'a': [1, 2, 'change'], 'b': 'change'}print dict3 # {'a': [1, 2, 'change'], 'b': 3}print dict4 # {'a': [1, 2], 'b': 3}
Add element
1, d['d'] = 4# Add directly through the subscript. If the key value already exists, then the element is modified. Of course, you can also access the element
Delete the element
1. d.clear()#Delete all elements in d
2.d.pop('a')#Delete the element with key value 'a'
3.del d ['a']#Delete the element with key value 'a'
Traverse the elements
for k in d:
print 'd[%s]=' % k,d[k]
or
for k,v in d.items():
print ' d[%s]=' % k,v
or
for k,v in d.iteritems():
print 'd[%s]=' % k,v
or
for k,v in d.viewitems():
print 'd[%s]=' % k,v
The difference between items(), iteritems() and viewitems()
items() of python2.x returns a list containing all elements of dict like the above, but because This was too much of a waste of memory, so I later added a set of functions (note: iteritems(), iterkeys(), and itervalues() (which began to appear in Python 2.2) to return an iterator to save memory, but the iterator cannot reflect The change of dict after calling this function. So viewitems() was added, which always represents the latest element. There is only one items function in Python 3.x, which is equivalent to viewitems() in 2.x.
Dictionary merging
1. dd = dict(dict1.items() + dict2.items())
However, this efficiency is not high. According to the above analysis guidance, it actually calls items to first return the corresponding list, then performs list addition, and finally initializes the list into a dictionary.
2, dd = dict(dict1, **dict2)
The keys of the dictionary must be strings. In Python 2 (the interpreter is CPython), we can use non-string keys as keys, but don't be fooled: this hack just happens to work in Python 2 using the standard CPython runtime environment.
The above statement is equivalent to
dd = dict1.copy()
dd.update(dict2)
where dd.update(dict2) is Equivalent to
for k in dict2
dd[k] = dict2[k]
It can be seen that the function of update can not only add non-existing elements, but also modify existing ones. The element value of the key.
And from the above, we know that dictionaries can also be merged through update and for...in.
Sort
dict = { : , : , : , : sorted(dict.items(), key= sorted(dict.items(), key= d: d[1]) ls = list(dict.keys()) ls.sort() for k in ls: print(k, dict[k]) for k in sorted(dict.keys()): print(k, dict[k])
The above is the detailed content of python dict dictionary detailed description. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
