字典是一个无序的数据集合,输出字典时,定义的顺序和输出的顺序不一致
>>> dict = {'1':'hello','2':'word'}
d = dict() ##定义空字典
print(d)
students = {
'03113009':{
'name':'tom',
'age':18,
'score':80
},
'03113010':{
'name': 'laoli',
'age': 19,
'score':30
}
}
print(students['03113010']['name'])
print({}.fromkeys({'1','2'},'03113009'))
d = {}
>>> dict = {'1':'hello','2':'word'}
>>> print(dict[1])
Traceback (most recent call last):
File "", line 1, in
KeyError: 1
>>> dict = {'1':'hello','2':'word'}
>>> print(dict[:1])
Traceback (most recent call last):
File "", line 1, in
TypeError: unhashable type: 'slice'
>>> dict = {'1':'hello','2':'word'}
>>> print('1' in dict)
True
>>> print('1' not in dict)
False
>>> for key in dict:
... print(key)
...
1
2
第一种:
>>> dict = {'1':'hello','2':'word'}
>>> for key in dict:
... print(key,dict[key])
...
1 hello
2 word
第二种:
>>> for key,value in dict.items():
... print(key,value)
...
1 hello
2 word
(1)字典的增
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应的key-value值
>>> service = {'mysql':3306,'http':8080}
>>> service['https'] = 443
>>> print(service)
{'mysql': 3306, 'http': 8080, 'https': 443}
>>> service['https'] = 7788
>>> print(service)
{'mysql': 3306, 'http': 8080, 'https': 7788}
update()
>>> print(service)
{'mysql': 3306, 'http': 8080, 'https': 7788}
>>> service_backup = {'tomcat':8080,'ssh':21}
>>> service.update(service_backup)
>>> print(service)
{'mysql': 3306, 'http': 8080, 'https': 7788, 'tomcat': 8080, 'ssh': 21}
#如果key值存在,不做修改
#如果key值不存在,则添加对应的key-value
>>> service.setdefault('http',9090)
8080
>>> service.setdefault('oracle',44575)
44575
>>> print(service)
{'mysql': 3306, 'http': 8080, 'https': 7788, 'tomcat': 8080, 'ssh': 21, 'oracle': 44575}
(2)删除
>>> service = {
... 'http':80,
... 'ftp':21,
... 'ssh':22
... }
>>> del service['http']
>>> print(service)
{'ftp': 21, 'ssh': 22}
#如果key存在,删除,并且返回删除key对应的value
#如果key不存在,报错
>>> item = service.pop('ftp')
>>> print(item)
21
>>> print(service)
{'ssh': 22}
>>> service = {'mysql':3306,'http':8080}
>>> item = service.popitem()
>>> print('删除的key-value对是:',item)
删除的key-value对是: ('http', 8080)
>>> print(service)
{'mysql': 3306}
>>> service.clear()
>>> print(service)
{}
(3)查找
注意:查看key的value值;key不存在,报错
>>> service = {'mysql':3306,'http':8080,'ssh':22}
>>> service.keys()
dict_keys(['mysql', 'http', 'ssh'])
>>> service.values()
dict_values([3306, 8080, 22])
#获取指定key对应的value值
#如果key不存在,默认返回None,如果需要指定返回值,传值即可
>>> service = {'mysql':3306,'http':8080,'ssh':22}
>>> service.get('http',9090)
8080
>>> service.get('oracle',9090)
9090
第一种:
for k,v in s.items():
print(k,v)
第二种:
for k,v in service.items():
print(k,'--->',v)
练习1:
#数字重复统计:
1)随机生成1000个整数;
2)数字范围[20,100];
3)升序输出所有不同的数字及其每个数字重复的次数
"""
import random
num_dict = {}
#统计数字及对应的次数
for i in range(1000):
num_key = random.randint(20,101)
if num_key in num_dict:
num_dict[num_key] += 1
else:
num_dict[num_key] = 1
#排序,遍历输出
for i in sorted(num_dict.keys()):
print("%d,%d" %(i,num_dict[i]))
练习2:
重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;
"hello java hello python"
# hello 2
# java 1
# python 1
input_str = input("请输入:")
str_dict = {}
split_str = input_str.split(' ')
for i in split_str:
if i in str_dict:
str_dict[i] += 1
else:
str_dict[i] = 1
#输出字典内容
print(str_dict)
for key,value in str_dict.items():
print(key,value)
练习3:
"""
1. 随机生成100个卡号;
卡号以6102009开头, 后面3位依次是 (001, 002, 003, 100>),
2. 生成关于银行卡号的字典, 默认每个卡号的初始密码为"redhat";
3. 输出卡号和密码信息, 格式如下:
卡号 密码
6102009001 000000
"""
import random
cardnum_dict = {}
key = 6102009000
for i in range(100):
cardnum_dict[key + i] = 'redhat'
print("卡号\t\t\t密码")
for key,value in cardnum_dict.items():
print("\n%d\t%s"%(key,value))