Python中的字典及其应用

一.字典创建 1.赋值创建字典 #赋值创建字典,key-value—-键值对 In [1]: d = {'key1': 'value', 'key2': 'value2'}

In [2]: print d {'key2': 'value2', 'key1': 'value'}

In [3]: services = {'ssh': 22, 'ftp':[20, 21], 'http':[80, 8080]}

In [4]: print services {'ftp': [20, 21], 'http': [80, 8080], 'ssh': 22}

2.通过工厂函数创建字典 In [6]: users = dict(user1='123',user2='456',user3='789')

In [7]: print users {'user2': '456', 'user3': '789', 'user1': '123'}

3.通过字典的fromkeys方法创建字典,所有元素有一个默认值 #如果没有指定默认值,默认值为None In [8]: print {}.fromkeys('hello') {'h': None, 'e': None, 'l': None, 'o': None} #给每个元素设置默认值为'123'

In [9]: print {}.fromkeys(['user1', 'user2', 'user3'], '123') {'user2': '123', 'user3': '123', 'user1': '123'}

应用案例: 生成多个银行卡号,并初始化密码为"000000" # 卡号由 6 位组成, 前 3 位是 610 , 后面的依次是 001, 002, 003...100 [root@localhost code1]# vim cards.py

#!/usr/bin/env python #coding:utf-8 cards = [] for i in range(1,101): a = '610%.3d' %(i) cards.append(a) print {}.fromkeys(cards,'000000')

二.分析字典的特征(跟元组和列表比较) -字典不能索引和切片,因为字典是无序的数据类型; -字典不支持重复和连接; -字典支持成员操作符: 判断字典的key值是否在字典中存在; in, not in 三.字典的增删改查 1.增 -字典名[key] = value -d.update(a=1, b=2) -d.update({'a':1, 'b',2}) -d.setdefault('a', 1)

(1)通过字典名[key]=value,将key-value添加到字典中 In [10]: service = {'ftp':[20,21]} In [11]: service['http'] = [80,8080]

In [12]: service Out[12]: {'ftp': [20, 21], 'http': [80, 8080]}

(2)update方法实现添加:key存在,覆盖value值,否则添加 In [21]: service = {'ftp':[20,21]}

In [22]: service1 = {'ssh':22}

In [23]: service.update(service1)

In [24]: print service {'ftp': [20, 21], 'ssh': 22}

(3)update添加 In [25]: print service {'ftp': [20, 21], 'ssh': 22}

In [27]: service.update(http=[80,8080],ftp=23)

In [28]: print service #覆盖value值 {'ftp': 23, 'http': [80, 8080], 'ssh': 22}

(4)setdefault实现添加: key存在,不覆盖value值,否则,添加

In [30]: service = {'ftp':[20,21]} In [32]: service.setdefault('ftp',23) Out[32]: [20, 21]

In [33]: print service {'ftp': [20, 21]} #key存在不覆盖value值 In [34]: service.setdefault('ssh',23) Out[34]: 23

In [35]: print service {'ftp': [20, 21], 'ssh': 23} #key不存在,添加

2.改 -字典名[key]=value -d.update({'a':2, 'b':3}) -d.update(a=2, b=3) 3.查 -查看key值; -查看value值; -查看key-value键值对; -查看key是否存在;

(1)查看key值 In [38]: services Out[38]: {'cc': 23, 'ftp': [20, 21], 'http': [80, 8080], 'ssh': 22}

In [40]: services.keys() Out[40]: ['cc', 'ftp', 'http', 'ssh']

In [41]: services.viewkeys() Out[41]: dict_keys(['cc', 'ftp', 'http', 'ssh']) #给key起名字

In [45]: services.iterkeys() Out[45]: <dictionary-keyiterator at 0x2887730>

(2)查看value值 n [46]: services.values() Out[46]: [23, [20, 21], [80, 8080], 22]

(3)查看key-value键值对 In [47]: services.items() Out[47]: [('cc', 23), ('ftp', [20, 21]), ('http', [80, 8080]), ('ssh', 22)]

(4)查看key是否存在 In [48]: services.has_key('http') Out[48]: True

In [49]: services.has_key('sttp') Out[49]: False

(5)查看指定key对应的value值 如果key不存在,不报错; 如果key存在,返回value值 In [50]: services.get('sttp') #key不存在,不报错

In [51]: services.get('http') Out[51]: [80, 8080] #key存在,返回value值

In [52]: services['sttp'] #key不存在,直接报错 KeyError Traceback (most recent call In [54]: services['http'] #key存在,返回value值 Out[54]: [80, 8080]

4.删

d.pop(key) #删除指定 key 的字典元素; d.popitem() #随机删除字典的 key-value 元素 ; del d[key] #删除指定 key 的字典元素; d.clear() #清空字典元素

四.循环遍历字典 In [82]: service Out[82]: {'ftp': 20, 'http': [80, 8080], 'ssh': 22} 1.遍历key-value的值 In [85]: for i,j in service.items(): ….: print i,j ….: ftp 20 http [80, 8080] ssh 22

2.默认情况下,遍历字典的key值 In [86]: for i in service: ….: print i ….: ftp http ssh

五.字典的应用 应用1: 通过字典实现case语句 -目前python不支持case语句; -实现case语句的两种方式: -if…elif…elif…else… -字典实现

#!/usr/bin/env python  #coding:utf-8  """  # 实现四则运算  # - 用户分别输入第一个数字,运算操作符,第三个数字;  # - 根据用户的运算操作打印出运算结果;  # """
if...elif...elif...else... 实现:    from __future__ import division  num1 = input()  ope = raw_input()  num2 = input()  if ope == '+':          print num1+num2  elif ope == '-':          print num1-num2  elif ope == '*':          print num1*num2  elif ope == '/':          print num1/num2  else:          print 'error operator'

字典实现 case 语句 #coding:utf-8 """ 实现四则运算 用户分别输入第一个数字,运算操作符,第三个数字; 根据用户的运算操作打印出运算结果; """

#!/usr/bin/env python #coding:utf-8 from future import division num1 = input() ope = raw_input() num2 = input() d = { "+" : num1+num2, "-" : num1-num2, "" : num1num2, "/" : num1/num2, } if not ope in d: print "error operator" else: print d[ope]

应用2:用户管理系统 -1.注册新用户 -如果注册用户已经存在,则报错; -需要填写信息: name, passwd, gender, email,age; -2.用户登录 要求同之前写的用户登录系统 -3.注销用户 用户注销时,需要输入用户名和正确的用户密码 -4.显示用户信息 显示系统中存在所有已经注册用户的信息; -5.退出系统。

欢迎评论