Home Backend Development Python Tutorial Python中字典创建、遍历、添加等实用操作技巧合集

Python中字典创建、遍历、添加等实用操作技巧合集

Jun 06, 2016 am 11:18 AM
python create dictionary Add to Traverse

字段是Python是字典中唯一的键-值类型,是Python中非常重要的数据结构,因其用哈希的方式存储数据,其复杂度为O(1),速度非常快。下面列出字典的常用的用途.
一、字典中常见方法列表

代码如下:


#方法                                  #描述 
------------------------------------------------------------------------------------------------- 
D.clear()                              #移除D中的所有项 
D.copy()                               #返回D的副本 
D.fromkeys(seq[,val])                  #返回从seq中获得的键和被设置为val的值的字典。可做类方法调用 
D.get(key[,default])                   #如果D[key]存在,将其返回;否则返回给定的默认值None 
D.has_key(key)                         #检查D是否有给定键key 
D.items()                              #返回表示D项的(键,值)对列表 
D.iteritems()                          #从D.items()返回的(键,值)对中返回一个可迭代的对象 
D.iterkeys()                           #从D的键中返回一个可迭代对象 
D.itervalues()                         #从D的值中返回一个可迭代对象 
D.keys()                               #返回D键的列表 
D.pop(key[,d])                         #移除并且返回对应给定键key或给定的默认值D的值 
D.popitem()                            #从D中移除任意一项,并将其作为(键,值)对返回 
D.setdefault(key[,default])            #如果D[key]存在则将其返回;否则返回默认值None 
D.update(other)                        #将other中的每一项加入到D中。 
D.values()                             #返回D中值的列表

二、创建字典的五种方法

方法一: 常规方法   

代码如下:


# 如果事先能拼出整个字典,则此方法比较方便
>>> D1 = {'name':'Bob','age':40} 


方法二: 动态创建

代码如下:

                 
# 如果需要动态地建立字典的一个字段,则此方法比较方便
>>> D2 = {} 
>>> D2['name'] = 'Bob' 
>>> D2['age']  =  40 
>>> D2 
{'age': 40, 'name': 'Bob'}


方法三:  dict--关键字形式      

代码如下:


# 代码比较少,但键必须为字符串型。常用于函数赋值
>>> D3 = dict(name='Bob',age=45) 
>>> D3 
{'age': 45, 'name': 'Bob'}

方法四: dict--键值序列

代码如下:


# 如果需要将键值逐步建成序列,则此方式比较有用,常与zip函数一起使用
>>> D4 = dict([('name','Bob'),('age',40)]) 
>>> D4 
{'age': 40, 'name': 'Bob'}



代码如下:


>>> D = dict(zip(('name','bob'),('age',40))) 
>>> D 
{'bob': 40, 'name': 'age'} 


方法五: dict--fromkeys方法# 如果键的值都相同的话,用这种方式比较好,并可以用fromkeys来初始化

代码如下:


>>> D5 = dict.fromkeys(['A','B'],0) 
>>> D5 
{'A': 0, 'B': 0} 


如果键的值没提供的话,默认为None

代码如下:


>>> D3 = dict.fromkeys(['A','B']) 
>>> D3 
{'A': None, 'B': None} 

三、字典中键值遍历方法

代码如下:


>>> D = {'x':1, 'y':2, 'z':3}          # 方法一 
>>> for key in D: 
    print key, '=>', D[key]   
y => 2 
x => 1 
z => 3 
>>> for key, value in D.items():       # 方法二 
    print key, '=>', value    
y => 2 
x => 1 
z => 3 
 
>>> for key in D.iterkeys():           # 方法三 
    print key, '=>', D[key]   
y => 2 
x => 1 
z => 3 
>>> for value in D.values():           # 方法四 
    print value  



>>> for key, value in D.iteritems():   # 方法五 
    print key, '=>', value 
     
y => 2 
x => 1 
z => 3 

Note:用D.iteritems(), D.iterkeys()的方法要比没有iter的快的多。

四、字典的常用用途之一代替switch

在C/C++/Java语言中,有个很方便的函数switch,比如:

代码如下:


public class test { 
     
    public static void main(String[] args) { 
        String s = "C"; 
        switch (s){ 
        case "A":  
            System.out.println("A"); 
            break; 
        case "B": 
            System.out.println("B"); 
            break; 
        case "C": 
            System.out.println("C"); 
            break; 
        default: 
            System.out.println("D"); 
        } 
    } 

在Python中要实现同样的功能,
方法一,就是用if, else语句来实现,比如:

代码如下:


from __future__ import division 
 
def add(x, y): 
    return x + y 
 
def sub(x, y): 
    return x - y 
 
def mul(x, y): 
    return x * y 
 
def div(x, y): 
    return x / y 
 
def operator(x, y, sep='+'): 
    if   sep == '+': print add(x, y) 
    elif sep == '-': print sub(x, y) 
    elif sep == '*': print mul(x, y) 
    elif sep == '/': print div(x, y) 
    else: print 'Something Wrong' 
 
print __name__ 
  
if __name__ == '__main__': 
    x = int(raw_input("Enter the 1st number: ")) 
    y = int(raw_input("Enter the 2nd number: ")) 
    s = raw_input("Enter operation here(+ - * /): ") 
    operator(x, y, s) 

方法二,用字典来巧妙实现同样的switch的功能,比如:

代码如下:


#coding=gbk 
 
from __future__ import division 
 
x = int(raw_input("Enter the 1st number: ")) 
y = int(raw_input("Enter the 2nd number: ")) 
 
def operator(o): 
    dict_oper = { 
        '+': lambda x, y: x + y, 
        '-': lambda x, y: x - y, 
        '*': lambda x, y: x * y, 
        '/': lambda x, y: x / y} 
    return dict_oper.get(o)(x, y) 
  
if __name__ == '__main__':   
    o = raw_input("Enter operation here(+ - * /): ") 
    print operator(o) 

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles