search
HomeBackend DevelopmentPython Tutorialpython 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft