10.Python学习之字典的使用方法

        字典(dictionary)是Python中另一个非常有用的内置数据类型。列表、元组都是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取(即可以通过索引来读取)。

        字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。键(key)必须使用不可变类型。在同一个字典中,键(key)必须是唯一的。

1.字典的创建:

我们需要注意的是:

1)字典是一个无序的数据集合,使用print输出字典的时候
2)通常输出的顺序和定义的顺序是不一致的

1)创建字典的一般方法:

#创建字典的一般方法
#字典:key - value 键值对
#value可以是任意数据类型
s = {
    'Linux':[100,99,88],
    'Python':[190,564,645]
}

print(s,type(s))

结果:

                                                    

2)空字典的创建:

s = {}
print(type(s))

结果:          

                                        

3)工厂函数:

#工厂函数
d = dict()
print(type(d))

d1 = dict(a=1,b=2)
print(d1,type(d1))

结果:

                                                     

4)字典的嵌套:

字典中可以嵌套字典,已达到我们想要表达的目的:

#字典的嵌套
students = {
    '03164067':{
        'name':'wf',
        'age':21,
        'score':80
    },
    '03164068':{
        'name': 'lee',
        'age': 22,
        'score': 59
    }
}
print(students['03164067']['name'])

结果:

                                 

5)多值映射:

#所有的key对应的value值是一样的
print({}.fromkeys({'1','2'},'000000'))

结果:

                                            

2.字典的特性:

d = {
    '1':'a',
    '2':'b'
}
#成员操作符
print('1' in d)

#for循环,默认遍历字典的key值
for i in d:
    print(i)

#遍历字典
for i in d:
    print(i,d[i])

结果:

                                     

3.字典的增加:

#增加一个元素
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应key-value
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

services['mysql'] = 3306
print(services)

services['http'] = 443
print(services)

结果:

                                                         

 添加多个键值对:

#添加多个key-value值
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

services_backup = {
    'https':443,
    'tomcat':8080,
    'http':8080
}
services.update(services_backup)
print(services)

services.update(flask=9000,http=8000)
print(services)

结果:

                                       

setdefault添加key值:
#setdefault添加key值
#如果key值存在,不做修改
#如果key值不存在,添加对应的key-value
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

services.setdefault('http',9090)
print(services)

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

结果:

                                            

4.字典的删除:

1)从内存中删除:

services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)
del services['http']
print(services)

结果:

                                           

2)pop删除指定元素:

#pop删除指定key的key-value
#如果不存在,报错
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)

item = services.pop('http')      #如果key存在,删除,并返回删除key对应的value
print(item)
print(services)

结果:

                                                     

3)popitem删除最后一个元素:

#popitem删除最后一个key-value值
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)

item = services.popitem()
print('删除的是:',item)
print(services)

结果:

                                                   

4)清空字典内容

#清空字典内容
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)

services.clear()
print(services)

结果:

                                                  

5.字典的查看:

services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

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

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

结果:

                                           

services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

#查看字典的key-value值
print(services.items())

#查看key的value值
#key不存在,默认返回none
#key不存在,有default值,则返回default值
print(services.get('http'))
print(services.get('https','key not exist'))

结果:

                                          

#遍历
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
for k,v in services.items():
    print(k,'--->',v)

for k in services:
    print(k,'--->',services[k])

结果:

                                               

6.字典综合练习:

 重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.>;
    # 1. 用户输入一句英文句子;
    # 2. 打印出每个单词及其重复的次数;
 "hello java hello python"
# hello 2
# java 1
# python 1
s = input('s:')

#1.把每个单词分割处理
s_li = s.split()
print(s_li)

#通过字典存储该单词和其出现的次数

word_dict = {}

"""
依次循环遍历列表
    如果列表元素不在字典的key中,将元素作为key 1作为value值
    如果列表元素在字典的key中,直接更新元素的value值,在原有的基础上加1
"""
for item in s_li:
    if item not in word_dict:
        word_dict[item] = 1
    else:
        word_dict[item] += 1

print(word_dict)

结果:

                                 

原创文章 43 获赞 15 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41975471/article/details/89200230