Python 基础 1.元组操作 2.字典操作 3.集合操作 4.公共操作

1.元组操作

 

2.字典操作

 

 输出的值如下

 

 

# 定义字典
dict1 = {"name": "顺顺", "age": "20"}
print(dict1, type(dict1))

# 给字典添加一对键值对 从后面添加
dict1["gender"] = "man"
print(dict1,type(dict1))

# 删除键值对
del dict1["gender"]
print(dict1, type(dict1))

# 清空键值对  clear
dict1.clear()
print(dict1, type(dict1))

# 查找   {键: 值}
dict2 = {"name": "峰峰", "age": "25"}
print(dict2["name"])     #查找指定键 对应的值1
# print(dict2["gender"])  查找没有的键 则报错

print(dict2.get("age"))  #查找年龄
print(dict2.get("id"))  #查找没有的键 则返回None
print(dict2.get("id", 110))  #查找没有的键 则返回默认值

# 查找所有的键
dict3 = {"name": "Simon", "age": "36", "height": 138}
print(dict3.keys(), type(dict3.keys()))  #查找所有的键  组成一个列表
print(dict3.values(), type(dict3.values()))  #查找所有的值  组成一个列表
# 查找所有的键值对  组成一个列表 里面是每一对键值对都是元祖
print(dict3.items()), type(dict3.items())


print("=================================")
# 字典的遍历
# 遍历的是字典的键
for key in dict3.keys():
    print(key)

print("===================")
# 遍历的是字典的值
for value in dict3.values():
    print(value)

print("===================")
# 遍历字典所有的键对值
for k, v in dict3.items():
    print(k, v)

3.集合操作

 

 

set1 = {1, 3, 5}
print(set1)

# 增加数据 到集合中
set1.add("张三")
print(set1)

# update表示更新数据  集合的特点之一  不能有重复数据 可以作为序列的去重工具
set1.update([1, 2])
print(set1)

# 会将字符串abc拆开加入到集合中 且发现集合是没有顺序的
set1.update("abc")
print(set1)

# 删除数据
set1.remove("张三")
print(set1)
# 删除不存在的值  报错
# set1.remove("李四")
# print(set1)
set1.discard("a")
print(set1)

set2 = {1, 2, "张飞"}
set2.discard(1)
print(set2)

#删除不存在的值 不报错
set2.discard(3)
print(set2)

# 随机弹出一个值 返回的是随机值
set3 = {5, 2, 3, 4, 1}
rst = set3.pop()
print(rst)

 4.公共操作

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值