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

作者:junjie 时间:2021-04-02 08:22:12 

字段是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) 

标签:Python,字典,创建,遍历,添加,操作技巧
0
投稿

猜你喜欢

  • Python实现针对json中某个关键字段进行排序操作示例

    2023-03-28 16:02:37
  • Python实现破解网站登录密码(带token验证)

    2021-09-29 06:22:22
  • python实现扫雷小游戏

    2023-02-15 11:58:58
  • Python监听键盘和鼠标事件的示例代码

    2022-06-14 07:05:23
  • pycharm 中mark directory as exclude的用法详解

    2021-02-27 05:24:07
  • python每5分钟从kafka中提取数据的例子

    2022-05-15 16:35:52
  • Python pip安装lxml出错的问题解决办法

    2021-11-17 07:36:07
  • Jupyter Notebook读取csv文件出现的问题及解决

    2023-08-09 23:11:50
  • Python打印不合法的文件名

    2021-06-29 03:40:19
  • flask中使用SQLAlchemy进行辅助开发的代码

    2021-09-10 07:46:43
  • Python 下载Bing壁纸的示例

    2023-11-20 00:14:41
  • python实战之实现excel读取、统计、写入的示例讲解

    2022-02-12 17:42:15
  • 利用ADODB.Stream使用浏览器下载服务器文件

    2008-10-09 12:42:00
  • Python实现DBSCAN聚类算法并样例测试

    2022-04-22 22:25:48
  • Python asyncore socket客户端实现方法详解

    2022-06-18 14:17:42
  • Python基于百度AI实现抓取表情包

    2022-05-01 00:01:35
  • python实现地牢迷宫生成的完整步骤

    2021-07-26 19:27:56
  • Python中使用第三方库xlrd来读取Excel示例

    2022-04-22 06:29:41
  • Python通过Manager方式实现多个无关联进程共享数据的实现

    2021-12-27 04:03:17
  • 纯CSS圆角框

    2009-12-11 18:57:00
  • asp之家 网络编程 m.aspxhome.com