Python字典、集合详解

字典的创建

'''
字典里面的数据是以键值对形式出现,字典数据和数据顺序没有关系,
即字典不支持下标,后期无论数据如何变化,只需要按照对应的键的名字来查找数据即可
'''


# 字典特点: 1. 符号为大括号 2. 数据为键值对形式出现  3. 各个键值对之间用逗号隔开
# 符合上面三个条件就是字典,字典不支持下标。
# {} 里面放入键值对,用逗号隔开


# 创建有数据的字典
dict1 = {'name' : 'tom', 'age' : 18, 'gender': '男'}
# 查看一下dict1的数据类型
print(type(dict1))   # <class 'dict'>


# 创建空字典
dict2 = {}
print(type(dict2))  # <class 'dict'>


# 用dict()函数来创建空字典
dict3 = dict()
print(type(dict3))
print(dict3)  # 输出 {}

字典常用操作(增、删、改、查)

新增数据


'''
新增数据的写法:字典序列[key] = 值
 这里的字典为可变类型,打印原字典名,就能看到修改新增之后的数据。之前的元组是不可变类型,是不能修改内部数据的。
注意: 如果key存在则修改这个key对应的值;如果key不存在则新增此键值对
'''


dict1 = {'name': 'TOM' , 'age':20 , 'gender': '男' }


# name这个键存在这个字典中,所以修改键值对
dict1['name'] = 'ROSE'
print(dict1)  # 输出修改后的字典 {'name': 'ROSE', 'age': 20, 'gender': '男'}


# id这个key不存在这个字典中,所以新增此键值对
dict1['id'] = 110
print(dict1)   # 输出新增后的字典{'name': 'TOM', 'age': 20, 'gender': '男', 'id': 110}

删除数据


dict1 = {'name': 'TOM', 'age': 20 , 'gender': '男'}


# 1.del 删除字典或指定的键值对


# 删除字典
# del(dict1)
# print(dict1)   # 报错,说明已经删除了


# 删除指定的字符串
# del dict1['name']  # 删除key为name的键值对
# del dict1['names']  # 如果删除的内容不存在就会报错
# print(dict1)		# {'age': 20, 'gender': '男'}


# 2. clear() 清空字典
dict1.clear()
print(dict1)      # 输出{}

修改数据


dict1 = {'name':'tom', 'age':20 , 'gender':'男'}


# dict1['name'] = 'lily'
# print(dict1)     # {'name': 'lily', 'age': 20, 'gender': '男'}


dict1['id'] = 2020
print(dict1)    # {'name': 'tom', 'age': 20, 'gender': '男', 'id': 2020}

查找数据


# 可迭代的对象指代的是可以用for遍历的对象


dict1 = {'name':'tom', 'age': 20 , 'gender':'男'}


# 1. [key]
# print(dict1['name'])    #  输出tom 
# print(dict1['names'])   # 如果查找的值是不存在的key,则会报错


# 2.函数


# 2.1 get()
# 语法: 字典序列.get(key,默认值)


# print(dict1.get('name'))   # tom
# print(dict1.get('names'))  # 如果键值不存在,返回None
# print(dict1.get('names','不存在')) # 如果键值不存在,返回“不存在”


# 2.2 keys() 查找字典中所有的key,返回可迭代对象
print(dict1.keys())  # 输出 dict_keys(['name', 'age', 'gender'])


# 2.3 value() 查找字典中所有的value,返回可迭代对象
print(dict1.values())  # 输出 dict_values(['tom', 20, '男'])


# 2.4 items() 查找字典中所有的键值对,返回可迭代对象,里面的数据是元组,元组数据1是字典的key,元组数据2是字典key对应的值
print(dict1.items())  # 输出dict_items([('name', 'tom'), ('age', 20), ('gender', '男')])

字典的遍历

# key遍历


dict1 = {'name':'tom', 'age':20 , 'gender': '男'}


for key in dict1.keys():
    print(key)
'''
输出结果:
       name
       age
       gender
'''    


==================================================================


# value遍历


dict1 = {'name':'tom', 'age':20, 'gender':'男'}


for value in dict1.values():
    print(value)
    
'''
输出结果:
		tom
		20
		男
'''
=====================================================================


# 键值对遍历
# dict1.items 可迭代对象的内部是元组
dict1 = {'name':'tom', 'age': 20 , 'gender': '男'}
for item in dict1.items():
    print(item)
'''
输出结果:
        ('name', 'tom')
        ('age', 20)
        ('gender', '男')
'''


=====================================================================


# 键值对拆包遍历


dict1 = {'name':'tom', 'age':'20', 'gender':'男'}


# xx.items():返回可迭代对象,内部是元组,元组有2个数据
# 元组数据1是字典的key,元组数据2是字典的value


for key,value in dict1.items():
    # print(key)
    # print(value)
    print(f'{key}={value}')


'''
输出的内容是:


    	name=tom
   		age=20
    	gender=男
'''

字典小总结

定义字典
dict1 = {'name':'TOM', 'age':30}
dict2 = {}
dict3 = dict()


常见操作
    增/改
字典序列[key] = 值


查找
    字典序列[key]
    keys()
    values()
    items()

集合的创建

'''
1 .集合有一个特点:去重,也就是说集合当中的数据是没有重复的,如果有不允许重复的数据出现的时候,这是用用集合存储数据即可。
2. 创建集合使用{} 或 set();但是如果要创建空集合只能使用set(),因为 {} 用来创建空字典的
3. 数据的展示循序跟写代码的顺序不一样,集合没有顺序,因为没有顺序,所以不支持下标的操作。
'''


# 1. 创建有数据的集合
s1 = {10,20,30,40,50}
print(s1)


s2 = {10,20,30,20,30}
print(s2)     #{10, 20, 30} 输出结果 因为有去重功能


s3 = set('姓名')
print(s3)     # {'姓', '名'}


# 2.创建新集合
s4 = set()
print(s4)		# set()
print(type(s4))   # <class 'set'>


# 这里不能用{}来创建新集合
s5 = {}
print(type(s5)) # 输出的结果是<class 'dict'> ,因为这时字典的创建方式

集合常见操作(增、删、查)

增加数据


s1 = {10,20}
# 1. 集合是可变类型
# add() 用来增加一个单一数据到原集合当中来
s1.add(100)
print(s1)      # {100, 10, 20}


# 集合有去重功能,如果追加的数据是集合已有数据,则什么事情都不做
s1.add(100)
print(s1)


# update() 用来增加一个数据序列到原集合当中来
s1.update([10,20,30,40,50])
print(s1)  # 输出 {100, 40, 10, 50, 20, 30} 有去重功能,如果添加的数据原集合中有的,则不进行操作。


# s1.update(299) 不能直接添加单一数据
s1.update([299]) # 这种方式的添加就可以
print(s1)

删除数据


s1 = {10,20,30}
s2 = {10,20,30}
s3 = {10,20,30}
# 1. remove():删除指定数据,如果数据不存在则报错
s1.remove(10)
print(s1)  # {20, 30}


# s1.remove(333)
# print(s1)  # 报错,以为删除的没有这个数据


============================================================================


# 2. discard():删除指定数据,如果数据不存在不报错
s2.discard(10)
print(s2)  # 输出 {20, 30}


s2.discard(666)  # 就算删除的数据不存在也不会报错


============================================================================


# 3. pop():随机删除某个数据,并返回这个数据
del_num = s3.pop()  
print(del_num) 		 # 10
print(s1)		# {20, 30}

查找数据


s1 = {10,20,30,40}


# 用in和not in 判断数据10是否在集合中存在


print(10 in s1)  # Ture
print(10 not in s1)  # False

集合小总结

'''
创建结合
    有数据集合
        s1 = {数据1,数据2,...}
    无数据集合
        s1 = set()
        
常见操作
    增加数据
        add()
        update()
    删除数据
        remove()
        discard()
'''


 0
 0
 分享
评论图片
评论