小菜鸟的python进阶之路 ------- 字典

字典

  • 定义字典
  • 字典的特性
  • 字典的增、删、改、查

 

1..定义字典

字典是一个无序的数据集合,输出字典时,定义的顺序和输出的顺序不一致

  •  s = {}定义字典:key-value:value可以是任意类型
>>> 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'])
  • 所有的key和value值是一样的情况
print({}.fromkeys({'1','2'},'03113009'))

2.字典的特性

d = {}

  • 字典不支持索引
>>> dict = {'1':'hello','2':'word'}
>>> print(dict[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1
  • 字典不支持切片
>>> dict = {'1':'hello','2':'word'}
>>> print(dict[:1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'slice'
  • 字典的重复和连接无意义,因为字典的key值是唯一的
  • 成员操作符(in ,not in)
>>> dict = {'1':'hello','2':'word'}
>>> print('1' in dict)
True
>>> print('1' not  in dict)
False
  • for循环,默认遍历字典的key值
>>> 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

3.字典的增、删、查

(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}
  • 添加多个key-value值

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}

 

  • setdefault添加key值

#如果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)删除

  • del  字典[ ]
>>> service = {
...     'http':80,
...     'ftp':21,
...     'ssh':22
... }
>>> del service['http']
>>> print(service)
{'ftp': 21, 'ssh': 22}
  • pop(' ')   删除指定key的key-value

#如果key存在,删除,并且返回删除key对应的value
#如果key不存在,报错

>>> item = service.pop('ftp')
>>> print(item)
21
>>> print(service)
{'ssh': 22}
  • popitem()   删除最后一个key-value值
>>> service = {'mysql':3306,'http':8080}
>>> item = service.popitem()
>>> print('删除的key-value对是:',item)
删除的key-value对是: ('http', 8080)
>>> print(service)
{'mysql': 3306}
  • clear()  清空字典内容
>>> service.clear()
>>> print(service)
{}

 

(3)查找

  • keys()  #查看key的值
  • values() #查看value值

注意:查看key的value值;key不存在,报错

>>> service = {'mysql':3306,'http':8080,'ssh':22}
>>> service.keys()
dict_keys(['mysql', 'http', 'ssh'])
>>> service.values()
dict_values([3306, 8080, 22])
  • get('key','自定义default值')

#获取指定key对应的value值

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

>>> service = {'mysql':3306,'http':8080,'ssh':22}
>>> service.get('http',9090)
8080
>>> service.get('oracle',9090)
9090

 

 

4.字典遍历

第一种:

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))

                                       

猜你喜欢

转载自blog.csdn.net/sinceNow/article/details/86523885
今日推荐