文章目录
- 1、dict 字典
- 2、set
1、dict 字典
dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
eg:
姓名和分数
name_store = {"lum":80,"大名": 85,"小明":90}
print (name_store)
print (name_store["lum"])
#改变字典数值
name_store["lum"] = 101
print(name_store)
# 判断字典中是否存在某个key
print ( "lum" in name_store)
print (name_store.get("xiaoqianqian",-1))
# 删除 key
delate_1 = name_store.pop("小明")
print(name_store)
#字典增加
name_store["小钱钱"] = "满分"
print( name_store)
#遍历字典
for key,value in name_store.items():
print(key)
print(value)
#遍历字典所有键
for key in name_store.keys():
print (key)
#遍历字典所有值
for value in name_store.values():
print(value)
2、set
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
name_set = {"1","2","3"}
print (name_set)
#添加
name_set = {"1","2","3","2"}
print (name_set)
name_set.add("5")
print (name_set)
#删除
name_set.remove("1")
print (name_set)
name_set.pop()
print (name_set)
set_1 = {"1","2","3"}
set_2 = {"2","3","4"}
print (set_1 | set_2) #并集
print (set_1 & set_2) #交集