字典的操作

# 字典的定义 dict 字典
dict1 = {}
dict2 = dict()
print(dict1, type(dict1))
print(dict2, type(dict2))
# 大括号抱起 逗号分割 键值对之间 用冒号
# 1.没有顺序 无法通过下标进行查找
# 2.只能通过键进行查找
dict3 = {"name": "秦小天", "age": 20, "gender": "man"}
print(dict3, type(dict3))

dict1 = {"name": "fan", "sge": 18}
print(dict1, type(dict1))  # {'name': 'fan', 'sge': 18} <class 'dict'>

# 添加一对键值对
dict1["gender"] = "man"
print(dict1, type(dict1))  # {'name': 'fan', 'sge': 18, 'gender': 'man'} <class 'dict'>

# 删除键值对 del
del dict1["gender"]
print(dict1, type(dict1))  # {'name': 'fan', 'sge': 18} <class 'dict'>

# 清空键值对 .clear
dict1.clear()
print(dict1, type(dict1))  # {} <class 'dict'>

# 查找 {键:值}  .get()
dict2 = {"name": "shun", "age": 25}
print(dict2["name"])  # shun
# print(dict2["hei"])  # 没有会报错

print(dict2.get("age"))  # 25
print(dict2.get("hei"))  # 查找没有的键会返回None
print(dict2.get("hei", 1))  # 没找到会返回后面的值

# 查找所有键
dict3 = {"name": "shun shun", "age": 25, "height": 170}
# 查找所有的键 组成列表
print(dict3.keys(), type(dict3.keys()))  # dict_keys(['name', 'age', 'height']) <class 'dict_keys'>
# 查找所有的值 组成列表
print(dict3.values(), type(dict3.values()))  # dict_values(['shun shun', 25, 170]) <class 'dict_values'>
# 查找键值对 组成列表 没对键值对都是元组
print(dict3.items(), type(dict3.items()))
# dict_items([('name', 'shun shun'), ('age', 25), ('height', 170)])  <class 'dict_items'>

print("========================================")
# 字典的遍历
# 遍历键
for key in dict3.keys():
    print(key)
# name
# age
# height
print("========================================")
# 遍历值
for val in dict3.values():
    print(val)
# shun shun
# 25
# 170
print("========================================")
# 遍历字典的键和值
for k, v in dict3.items():
    print(k, ":", v)
# name : shun shun
# age : 25
# height : 170




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值