一、字典的定义
在 Python 中,字典 是一系列键 — 值对 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何 Python 对象用作字典中的值。
在 Python 中,字典用放在花括号 {} 中的一系列键 — 值对表示
简单示例:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
测试:
green
5
空字典的定义:
>>> s = {}
>>> print(s,type(s))
({}, <type 'dict'>)
字典的定义:
s = {
'linux':[100,99,88],
'python':[190,34,56]
}
print(s,type(s))
测试:
{'linux': [100, 99, 88], 'python': [190, 34, 56]} <class 'dict'>
注意:键和值之间用冒号分隔,而键 — 值对之间用逗号分隔。
工厂函数
>>> d = dict()
>>> print(d,type(d))
({}, <type 'dict'>)
>>> d = dict(a=1,b=2)
>>> print(d,type(d))
({'a': 1, 'b': 2}, <type 'dict'>)
字典的嵌套
student = {
'123456':{
'name':'tom',
'age':'18',
'score':99
},
'657567':{
'name':'lily',
'age':'17',
'score':100
}
}
print(student['123456'])
print(student['123456']['name'])
测试:
{'name': 'tom', 'age': '18', 'score': 99}
tom
二、字典的特性
1.字典不支持切片
d = {
'1':'a',
'2':'b'
}
print(d[:])
测试:
2.成员操作符(针对key)
= {
'1':'a',
'2':'b'
}
print('1' in d)
print('1' not in d)
测试:
True
False
3.for循环(默认遍历的是key)
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key)
测试:
1
2
遍历字典
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key,d[key])
测试:
1 a
2 b
三、字典的常用方法
1.添加键-值对
01.增加一个元素
如果key值不存在,则添加对应的key-value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
service['mysql'] = 3306
print(service)
测试:
{'http': 80, 'ftp': 21, 'ssh': 22, 'mysql': 3306}
如果key值存在,则更新对应的value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
service['http'] = 443
print(service)
测试:
{'http': 443, 'ftp': 21, 'ssh': 22}
02.添加多个key-value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
service_backup = {
'1':443,
'tomcat':8080,
'http':8080
}
service.update(service_backup)
print(service)
测试:
{'http': 8080, 'ftp': 21, 'ssh': 22, '1': 443, 'tomcat': 8080}
或者:
service = {
'http':80,
'ftp':21,
'ssh':22
}
service.update(flask=9000,http=8000)
print(service)
测试:
{'http': 8000, 'ftp': 21, 'ssh': 22, 'flask': 9000}
03.setdefault添加key值
如果key值存在,不做修改
service = {
'http':80,
'ftp':21,
'ssh':22
}
service.setdefault('http',9090)
print(service)
测试:
{'http': 80, 'ftp': 21, 'ssh': 22}
如果key值不存在,则添加对应的key-value
service = {
'http':80,
'ftp':21,
'ssh':22
}
service.setdefault('oracle',44575)
print(service)
测试:
{'http': 80, 'ftp': 21, 'ssh': 22, 'oracle': 44575}
2.删除键-值对
01.del语句删除
service = {
'http':80,
'ftp':21,
'ssh':22
}
del service['http']
print(service)
测试:
{'ftp': 21, 'ssh': 22}
02.pop()删除指定key对应的value
如果key存在,删除,并且返回删除key对应的value(可以用变量去接收)
service = {
'http':80,
'ftp':21,
'ssh':22
}
item = service.pop('http')
print(item)
print(service)
测试:
80
{'ftp': 21, 'ssh': 22}
如果key不存在,直接报错
03.popitem()删除最后一个key-value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
item = service.popitem()
print('删除的key-value对是:',item)
print(service)
测试:
删除的key-value对是: ('ssh', 22)
{'http': 80, 'ftp': 21}
04.clear()清空字典内容
service = {
'http':80,
'ftp':21,
'ssh':22
}
service.clear()
print(service)
测试:
{}
3.字典的查看
01.查看字典的key值
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.keys())
测试:
dict_keys(['http', 'ftp', 'ssh'])
02.查看字典的value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.values())
测试:
dict_values([80, 21, 22])
03.查看字典的key-value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.items())
测试:
dict_items([('http', 80), ('ftp', 21), ('ssh', 22)])
04.查看key的value值
key不存在 默认返回None
key不存在,有defaule就返回defale的值
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.get('https',443))
测试:
443
练习题:
数字重复统计:
1). 随机生成1000个整数;
2). 数字的范围[20, 100],
3). 升序输出所有不同的数字及其每个数字重复的次数;
import random
all_num = []
for i in range(1000):
all_num.append(random.randint(20,100))
sorted_nums = sorted(all_num)
num_dict = {}
for num in sorted_nums:
if num in num_dict:
num_dict[num] += 1
else:
num_dict[num] = 1
print(num_dict)
重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;
s = input('请输入句子:')
s_li = s.split()
word_dict = {}
for i in s_li:
if i not in word_dict:
word_dict[i] = 1
else:
word_dict[i] += 1
print(word_dict)
1.随机生成100个卡号;
卡号以6102009开头, 后面3位依次是 (001, 002, 003, 100),
2.生成关于银行卡号的字典, 默认每个卡号的初始密码为"redhat";
3.输出卡号和密码信息, 格式如下:
卡号 密码
6102009001 000000
card_ids = []
for i in range(100):
s = '6102009%.3d' %(i + 1)
card_ids.append(s)
card_ids_dict = {}.fromkeys(card_ids,'redhat')
print('卡号\t\t\t\t 密码')
for key in card_ids_dict:
print('%s\t\t\t%s' %(key,card_ids_dict[key]))