一、字典的定义

使用键-值(key-value)存储,具有极快的查找速度
字典的键一般是唯一的,值可以取任意数据类型
字典是一个无序的数据集合
通常输出顺序和定义顺序不一样

示例:

users = [‘user1’,‘user2’]
passwds = [‘123’,‘456’]
print(zip(users,passwds))
print(list(zip(users,passwds)))		列表
print(dict(zip(users,passwds)))		字典

for i in zip(users,passwds):
    print(i)

python dict是否为空_for循环


== 字典中的value值可以是任意数据类型==

s = {
    'westos':[100,99,88],
    'redhat':[50,60,70]
}
print(s,type(s))

python dict是否为空_mysql_02


工厂函数

d = dict()			字典
print(d)
print(type(d))

d = dict(a=1,b=2)	字典
print(d)
print(type(d))
print(d['a']) 		打印a的value值

python dict是否为空_python dict是否为空_03


字典的嵌套

students = {
    '03113009':{
        'name':'wsp',
        'age':18,
        'score':90
    },
    '12345678':{
        'name':'laoli',
        'age':36,
        'score':80
    }
}
print(students['12345678']['name'])			打印[12345678]学号学生的名字

python dict是否为空_mysql_04


设置所有的key的value值一样

print({}.fromkeys({'1','2'},'000000'))		key1,2的value值均为000000

python dict是否为空_mysql_05

二、字典的特性

字典不支持索引 切片
字典的重复 连接无意义,因为字典的key值唯一

d = dict(a=1,b=2)
print(d[0])    #不支持

python dict是否为空_mysql_06


输出key的value值

d = dict(a=1,b=2)
print(d['a'])
print(d['b'])

python dict是否为空_python dict是否为空_07


成员操作符

d = dict(a=1,b=2)
print('a' in d)
print('a' not in d)

python dict是否为空_数据类型_08


for循环(默认遍历key值)

d = dict(a=1,b=2)
for k in d:
    print(k,d[k])	k及k对应的value值

python dict是否为空_for循环_09

三、字典的增加

增加一个元素:一个key值只能对应一个value
如果key值存在,则覆盖原来的value更新对应的value值
如果key值不存在,添加key-value值对

services = {
    'http':80,
    'ftp':21,
    'mysql':3306
}

 services['ssh'] = 22		增加key-value值
 print(services)
 services['http'] = 443		key已存在,更新value值
 print(services)

python dict是否为空_for循环_10


update添加多个key-value值

services = {
        'http':80,
        'ftp':21,
        'mysql':3306
    }
services_backup = {
    'https':443,
    'tomcat':8080,
    'ssh':22
}

services.update(services_backup)
print(services)

python dict是否为空_数据类型_11

services = {
            'http':80,
            'ftp':21,
            'mysql':3306
        }
services.update(flask=9000,http=8000)		key已存在,更新value值
print(services)

python dict是否为空_mysql_12


setdefault添加key值

如果key值存在,不做修改

如果key值不存在,添加对应的key-value

services = {
                'http':80,
                'ftp':21,
                'mysql':3306
            }
services.setdefault('http',9090)	http已存在,不做修改
print(services)

services.setdefault('oracle',44575)
print(services)

python dict是否为空_数据类型_13

四、字典的删除

删除一个key,对应的value也会从字典中删除

services = {
    'http':80,
    'ftp':21,
    'mysql':3306
}

del services['http']		del删除指定的key
print(services)

python dict是否为空_数据类型_14


pop删除指定的key的key-value

如果key存在,删除,并返回删除key对应的value

如果key不存在,报错

services = {
        'http':80,
        'ftp':21,
        'mysql':3306
    }
item = services.pop('mysql')
print(item)
print(services)

python dict是否为空_for循环_15


popitem删除最后一个key-value值

services = {
            'http':80,
            'ftp':21,
            'mysql':3306
        }
 item = services.popitem()
 print(item)
 print(services)

python dict是否为空_数据类型_16


清空字典内容

services = {
            'http':80,
            'ftp':21,
            'mysql':3306
        }
services.clear()
print(services)

python dict是否为空_for循环_17

五、字典的查看

查看字典的key值

print(services.keys()) 查看字典的value值

print(services.values())

查看字典的key-value值对

print(services.items())

python dict是否为空_for循环_18


查看key的value值

print(services['http'])

python dict是否为空_python dict是否为空_19


get获取指定key值对应的value值

如果key值存在,返回对应的value值

如果key值不存在,默认返回None;有default,则返回default;如果需要指定返回值,传值即可

print(services.get('http'))		存在
print(services.get('https'))	不存在默认返回None
print(services.get('https','key not exist'))	不存在,指定返回值
print(services.get('firewall',9090))				不存在,指定返回值

python dict是否为空_for循环_20


for循环遍历

for k,v in services.items()
    print(k,'-->',v)

python dict是否为空_python dict是否为空_21

六、字典练习

1.在20-100中随机取数1000次,排序并统计每个数出现的次数

import random
num = []								定义一个空集合
for i in range(1000):		
    num.append(random.randint(20,100))

num_s = sorted(num)						排序并添加到字典中
num_dict = {}							 定义一个空字典

for n in num_s:			
    if n in num_dict:					遍历key
        num_dict[n] +=1					定义value值
    else:
        num_dict[n] = 1
print(num_dict)

python dict是否为空_python dict是否为空_22

2.生成100个银行卡,开头为6102009,结尾为001-100,密码为‘redhat’

card_num = []									定一个空列表
for i in range(100):
    card_num.append('6102009%.3d' %(i+1))		卡号自加1

card_info = {}.fromkeys(card_num,'redhat')		定义列表里的元素作为key,对应的value值为redhat

print('卡号\t\t\t 密码')
for k,v in card_info.items():					遍历key-value值对
    print(k,'\t',v)

python dict是否为空_for循环_23