07_字典

# 1.首先,字典是以键值对的形式进行存储数据的
# 字典的表示方式:{key:value, key2:value, ...}
# dic = {"jay": "周杰伦", "金毛狮王": "谢逊"}

# val = dic["jay"]
# print(val)

# 字典的 key 必须是可哈希的数据类型(不可变类型)
# 字典的 value 可以是任何数据类型
# dic = {[]:123}
# print(dic)

# dic = {"詹姆斯": ["孩子1", "孩子2"]}
# print(dic)


# 2.字典的增删改查
# 字典的增加
# dic = dict()
# dic["jay"] = "周杰伦"
# dic[2] = 3
# print(dic)

# # 字典的修改
# dic['jay'] = "昆凌"  #此时,字典中已经有了jay,此时执行的就是修改操作了
# print(dic)

# dic.setdefault("tom","哈哈")  #设置默认值,如果以前已经有了tom了,setdefault就不起作用了
# dic.setdefault("tom","xixi")  
# print(dic)

# 字典的删除
# dic.pop("jay")  #根据key删除
# print(dic)

# # 字典的查询
# print(dic["jay557775"])    #如果key不存在,程序会报错,当你确定你的key是没有问题的,可以用
# print(dic.get('jay555'))   #如果key不存在,程序返回None,当你不确定你的key可以用

# None
# a = None
# print(a)
# print(type(a))

# s = "" #空字符串和None不一样

# 例子
# dic = {
#     "赵四": "特别能歪嘴",
#     "刘能": "老,老四啊。。",
#     "大脚": "跟这个和那个搞对象",
#     "大脑袋": "瞎折腾",
# }
# name = input("请输入你想知道我们村的人的名字:")
# val = dic.get(name)
# if val is None:
#     print("俺们村没有这个人")
# else:
#     print(val)


# 字典进阶操作 --  循环和嵌套
# dic = {
#     "赵四": "特别能歪嘴",
#     "刘能": "老,老四啊。。",
#     "大脚": "跟这个和那个搞对象",
#     "大脑袋": "瞎折腾",
# }

# # 1.可以用for循环,直接拿到key
# for key in dic:
#     print(key, dic[key])

# 2.希望把所有的key全部都保存在一个列表中
# print(dic.keys())
# print(list(dic.keys()))

# 3.希望把所有的value都放在一个列表中
# print(list(dic.values()))

# 4.直接拿到字典中的key和value
# print(dic.items())
# for key,value in dic.items():       # 可以直接拿到字典所有的key和value
#     # print(item)  #确定item中只有两项元素
#     # key,value = item
#     print(key, value)

# a, b = (1, 2)   #元组或列表都可以执行该操作,该操作被称为解构(解包)
# print(a)
# print(b)
 
# 非常重要(****)
# for k, v in dic.items():
#     print(k,v)

# 字典的嵌套
# wangfeng = {
#     "name": "汪峰",
#     "age": "18",
#     "wife": {
#         "name": "皮特张",
#         "hobby": "演习",
#         "assistant": {
#             "name": "乔峰",
#             "age": 23,
#         }
#     },
#     "children": [
#         {"name": "孩儿1", "age": 2},
#         {"name": "孩儿2", "age": 2},
#         {"name": "孩儿3", "age": 2},
#     ]
# }

# # 汪峰妻子助手的名字
# # name = wangfeng["wife"]['assistant']["name"]
# # print(name)

# # 给wangfegn的第二个孩子加1岁
# wangfeng['children'][1]['age'] = wangfeng['children'][1]['age'] + 1
# print(wangfeng)


# 补充,字典的循环删除

dic = {
    "赵四": "特别能歪嘴",
    "刘能": "老,老四啊。。",
    "大脚": "跟这个和那个搞对象",
    "大脑袋": "瞎折腾",
}

temp = []
for key in dic:
    if key.startswith('大'):
        temp.append(key)
        # dic.pop(key)      # RuntimeError: dictionary changed size during iteration,循环时又改变了长度

for t in temp: # 循环列表,删除字典中的内容
    dic.pop(t)

print(dic)   

  

posted @ 2023-08-16 15:36  香菜哥哥  阅读(7)  评论(0编辑  收藏  举报