python_字典(dict)


一.字典创建

1.赋值创建字典

In [41]: d = {"key1","value1","key2","value2"}    # 赋值创建字典, key-value, 键值对

In [42]: print d
set(['key2', 'key1', 'value2', 'value1'])

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

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


2.通过工厂函数创建字典

In [45]: userinfo = dict(user1="123",user2="456",user3="789")

In [46]: print userinfo
{'user2': '456', 'user3': '789', 'user1': '123'}


3.通过字典的fromkeys方法创建字典,所有元素有一个默

In [50]: print {}.fromkeys("hello")  ##如果没有默认值,默认位None
{'h': None, 'e': None, 'l': None, 'o': None}
In [51]: print {}.fromkeys(["user1","user2","user3"],"123") ##给每个元素设置默认
值123
{'user2': '123', 'user3': '123', 'user1': '123')

4.练习

#!/usr/bin/env python
#coding:utf-8

'''
应用案例:
生成多个银行卡号
并初始化密码位“000000”
'''


cardids = []
for i in range(1,101):    ##i = 1,2,3....100
	a = "610%.3d" %i  ##a = 610001,610002,....610100
		cardids.append(a)

print {}.fromkeys(cardids,"000000") ##给每个卡号对应一样的密码
		
python_字典(dict)_第1张图片





二.分析字典的特性(和元组,列表做对比)


1.

In [53]: d = {}

In [54]: d["a"] = 1

In [55]: d
Out[55]: {'a': 1}

In [56]: d["d"] = 3

In [57]: d
Out[57]: {'a': 1, 'd': 3}

In [58]: d["c"] = 3

In [59]: d
Out[59]: {'a': 1, 'c': 3, 'd': 3} ##字典为无序的数据类型 所以字典不能索引和切片

2.字典不支持重复和连接


3.字典支持成员操作符:判断字典key值是否在字典中存在 支持in,not in

In [59]: d
Out[59]: {'a': 1, 'c': 3, 'd': 3}

In [60]: 'a' in d
Out[60]: True

updateIn [61]: 'e' in d
Out[61]: False





三.字典的增删改查


1.增

python_字典(dict)_第2张图片

(1)通过字典名[key]=value,将'key':value添加到字典中

In [63]: services = {"ftp":[20,21]}

In [64]: print services
{'ftp': [20, 21]}

In [65]: services['http'] = [80,8080]

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

(2)update方法实现添加

In [67]: services = {"ftp":[20,21]} ##用定义的方法赋值字典
In [70]: services1 = {'http' : [80,8080]}
In [71]: services.update(services1)   ##
key存在,覆盖value值, 否则,添加
 
   
  In [72]: print services{'ftp': [20, 21], 'http': [80, 8080]} 
  
 
  
(3)更建议使用

In [75]: services = {"ftp":[20,21]}
In [76]: services.update(http=[80,8080],ssh=22)

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


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

In [82]: d
Out[82]: {'a': 1, 'c': 3, 'd': 3}

In [83]: d.setdefault('a',3)
Out[83]: 1

In [84]: d.setdefault('z',5)
Out[84]: 5

In [85]: d
Out[85]: {'a': 1, 'c': 3, 'd': 3, 'z': 5}


2.改

python_字典(dict)_第3张图片

(1)update
(2)字典名[key]=value


3.查
python_字典(dict)_第4张图片

In [90]: services
Out[90]: {'ftp': [20, 21], 'http': [80, 8080]}
In [92]: services.
services.clear       
services.keys  # 查看key值
services.copy        
services.pop
services.fromkeys    
services.popitem
services.get  # 查看指定key对应的value值;如果key不存在,不报错; 如果存在,返回value值;       
services.setdefault
services.has_key  # 查看key是否存在   
services.update
services.items       
services.values  # 查看value值
services.iteritems   
services.viewitems
services.iterkeys # 查看key值    
services.viewkeys  # 给key起名字
services.itervalues  # 查看key-value键值对   
services.viewvalues


4.删
python_字典(dict)_第5张图片


(1)字典.pop()

In [3]: services = {"ssh":22, "ftp":[20,21], "http":[80, 8080]}
In [4]: services.pop('ftp')
Out[4]: [20, 21]

In [5]: services
Out[5]: {'http': [80, 8080], 'ssh': 22}



(2)字典.popitem()

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

In [7]: services.popitem('a')  ##删不存在的报错
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
----> 1 services.popitem('a')

TypeError: popitem() takes no arguments (1 given)

In [9]: services.popitem()  ##为空时随机删除字典的key-value元素;
Out[9]: ('ftp', [20, 21])

In [10]: services
Out[10]: {'http': [80, 8080], 'ssh': 22}


(3)字典.clear()

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

In [15]: services.clear()  ##清空字典元素

In [16]: services
Out[16]: {}

(4)del 字典['key']

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

In [19]: del s
%%script      %%system      %store        set           staticmethod
%%sh          %save         %sx           setattr       str
%%svg         %sc           %system       slice         sum
%%sx          %set_env      services      sorted        super

In [19]: del services['ssh']

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






四.循环遍历字典

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

In [22]: for i,j in services.items():
   ....:     print i,j
   ....:     
ftp [20, 21]
http [80, 8080]
ssh 22

In [23]: for i in services:  # 默认情况下遍历字典的key值;
   ....:     print i
   ....:     
ftp
http
ssh


五.字典应用

目前python不支持case语句;
实现case语句的两种方式:
if...elif...elif...else...
字典实现



六.练习


1.if...elif...else...实现case语句

#!/usr/bin/env python
#coding:utf-8

'''
实现四则运算
-用户分别输入第一个数字,运算操作符,第三个数字;
-根据用户的运算操作打印出运算结果;

'''
from __future__ import division
num1 = input()
ope = raw_input()
num2 = input()

# 用if...elif...else...实现 case语句

if ope == "+":
        print num1+num2
elif ope == "-":
        print num1-num2
elif ope == "*":
        print num1*num2
elif ope == "/":
        print num1/num2
else:
        print "error operator"
python_字典(dict)_第6张图片

2.字典实现case语句

#!/usr/bin/env python
#coding:utf-8

'''
实现四则运算
-用户分别输入第一个数字,运算操作符,第三个数字;
-根据用户的运算操作打印出运算结果;

'''


from __future__ import division

num1 = input()
ope = raw_input()
num2 = input()

d = {
        "+" : num1+num2,
        "-" : num1-num2,
        "*" : num1*num2,
        "/" : num1/num2,
}

if not ope in d:
        print "error operator"
else:
        print d[ope]
python_字典(dict)_第7张图片





















你可能感兴趣的:(python)