当前位置: 代码迷 >> 综合 >> python教程——字典(dict)
  详细解决方案

python教程——字典(dict)

热度:59   发布时间:2023-12-08 18:40:48.0

1.字典的创建

1】赋值创建字典

Dict={“k1”:”v1”,”k2”:”v2”}

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

Dict=dict(k1=”v1”,k2=”v2”) 注:括号内可以写也可以不写

3】通过fromkeys创建字典,所有元素有一个默认值,如果没有默认值,则默认为None

{}.fromkeys([“k1”,”k2”,”k3”],”123”)创建字典内容为三个key值,对应的值均为123

测试:生成银行卡并初始密码

#!/usr/bin python
#encoding:utf-8#**************************************#
#     Author     :wang                 #
#     Email      :wang@qq.com          #
#     Version    :                     #
#     Create_Date:2017-12-30 01:56:05  #
#     Description:                     #
#                                      #
#**************************************#print "#**************************************#"
print "                批量产生卡号"
print "#**************************************#"
head = "610"
test = []
for i in range(1,100):test.append(head+"%.3d"%(i))   #产生610001、610002....610100
test={}.fromkeys(test,"0"*6)
count = 0
for i,v in enumerate(test):print v+":"+test[v],if i%4 == 0 :    #每行显示4个数据print


2.分析字典的特性(跟元组和列表比较)

1字典不能索引和切片,因为字典是无序的数据类型;

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

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

3.字典的增删改查

1】增

Dict[k1]=v1使k1的值为v1

Dict.update()字典更新,括号里也可以是字典名称,key值存在,覆盖value值,否则添加。

Dict.setdefault(“a”,1)实现添加,key值存在,不覆盖value值,否则添加。

2】改

Dict[key]=value

Dict.update({‘a’:2,’b’:3})

Dict.update(a=2,b=3)

3】查

查看key

Dict.keys()

Dict.viewkeys()给所有key组成的列表起名字

Dict.iterkeys()

查看value:

Dict.values()

查看key-value键值对

Dict.items()

查看key是否存在:

Dict.has_key(“key”)

查看指定key对应的value值,如果key不存在,不报错,如果存在,返回value值:

Dict.get(“key”)

4】删

删除指定key的字典单元:

Dict.pop(key)

随即删除字典的key-value元素:

Dict.popitem()

删除指定key的字典元素:

Del Dict[key]

清空字典元素:

Dict.clear()

循环编历字典:

for  i,j  in  Dict.items():

Print i,j

4.字典应用

应用1: 通过字典实现case语句

目前python不支持case语句;

实现case语句的两种方式:

1if...elif...elif...else...

2字典实现

测试:四则运算

#!/usr/bin python
#encoding:utf-8#**************************************#
#     Author     :wang                 #
#     Email      :wang@qq.com          #
#     Version    :                     #
#     Create_Date:2017-12-30 03:43:57  #
#     Description:                     #
#                                      #
#**************************************#
from __future__ import division
print "#**************************************#"
print "               四则运算"
print "#**************************************#"#            字典
def fun1(operate,num1,num2):d = {"+" : "%d+%d=%d"%(num1,num2,num1+num2),"-" : "%d+%d=%d"%(num1,num2,num1-num2),"*" : "%d+%d=%d"%(num1,num2,num1*num2),"/" : "%d+%d=%d"%(num1,num2,num1/num2)}if operate in d:print d[operate]else:print "ERROR!!!!!"#			非字典
def fun2(operate,num1,num2):if operate == '+':print "%d + %d = %d"%(num1,num2,num1+num2)elif operate == '-':print "%d - %d = %d"%(num1,num2,num1-num2)elif operate == '*':print "%d X %d = %d"%(num1,num2,num1*num2)elif operate == '/':print "%d / %d = %.2f"%(num1,num2,num1/num2)else:print "ERROR!!!!!!!"
def main():while True:num1 = input("num1:")operate = raw_input("operate:")num2 = input("num2:")print "字典"fun1(operate,num1,num2)print "非字典"fun2(operate,num1,num2)if raw_input("是否继续(y/n):") == "n":break
if __name__ == "__main__":main()


5.应用2:用户管理系统

1注册新用户

如果注册用户已经存在,则报错;

需要填写信息: name, passwd, gender, email,age;

2用户登录 要求同之前写的用户登录系统

3注销用户 用户注销时,需要输入用户名和正确的用户密码

4显示用户信息 显示系统中存在所有已经注册用户的信息;

5退出系统

#!/usr/bin python
#encoding:utf-8#**************************************#
#     Author     :wang                 #
#     Email      :wang@qq.com          #
#     Version    :                     #
#     Create_Date:2017-12-29 21:16:03  #
#     Description:                     #
#                                      #
#**************************************#print "#**************************************#"
print "             用户登录系统"      
print "#**************************************#"username = ["tom","jary","haha"]
password = ["123","456","789"]
def display():print '''【1】用户登陆【2】用户注册【3】用户注销'''select = input("请选择(1/2/3):")return select
def denglu():count = 0user = raw_input("用户名:")while count < 3:paswd = raw_input("密 码:")if user in username:i = username.index(user)if paswd == password[i]:print "HELLO"breakelse:count +=1print "你已经登陆失败%d次,剩余%d次机会。"%(count,3-count)else:print "用户不存在!!!"else:print "out of time" 
def zhuce():while True:user = raw_input("用户名:")paswd1 = raw_input("设置密码:")paswd2 = raw_input("请再次输入密码:") if paswd2 == paswd1:username.append(user)password.append(paswd1)print "注册成功"breakelse:print "两次输入密码不一致,请重新输入"
def zhuxiao():user1 = raw_input("请输入用户名:")paswd1 = raw_input("请输入密码:")select = raw_input("是否删除(y/n)?")if select == "y":index = username.index(user1)del username[index]del password[index]print "注销成功".username.password
def main():select = display()while True:if select == 1:denglu()elif select == 2:zhuce()elif select == 3:zhuxiao()elif select not in [1,2,3]:print "选项无效,清重新选择!!!"a = raw_input("是否继续(y/n)?")if a == "n":break
if __name__=="__main__":main()