Python语法基础 一
Python语法基础 二
Python语法基础 三
Python数据结构-列表
Python数据结构-元组
Python数据结构-集合
Python-函数
1.字典
"""
字典(dict):键值对数据(key-value)
key:键
键的类型可以是:字符串、整数、浮点数、bool、元组
value:值
值的类型基本上都支持
声明:
变量名 = {}
变量名 = {"xxx":xxx,"xxx":xxx}
"""
# 增加数据 字典[key] = value
dic = {}
dic["name"] = "tony"
dic["age"] = 18
dic["gender"] = "男"
print(dic) # {'name': 'tony', 'age': 18, 'gender': '男'}
# 删除数据 pop(key)
dic.pop("gender")
print(dic) # {'name': 'tony', 'age': 18}
# 查找数据 字典[key]
name = dic["name"]
print(name) # tony
# 修改数据 字典[key] = newValue
dic["age"] = "20"
print(dic["age"]) # 20
# 通过输入往字典里面加入个人信息
# userInfo = {}
# while True:
# key = input("输入项目:")
# value = input("输入值:")
# userInfo[key]=value
#
# temp = input("是否继续录入(y/n):")
# if temp != "y":
# break
# print(userInfo)
2.字典常用方法
"""
python
字典的常用方法
update() 字典合并
setdefault() 添加键值对,添加规则:key存在则不处理,key不存在则添加
pop() 删除指定的键值对,并返回value
popitem() 删除最后一个键值对。并返回该键值对
clear() 清空字典
get() 根据key查找 查找的key不存在则返回None
keys() 获取所有的键
values() 获取所有的值
items() 获取所有的键值对
in 键存在吗?
not in 键不存在吗?
len
"""
# update
# dic = {"name": "tony"}
# dic1 = {"age": 20}
# dic.update(dic1)
# print(dic) # {'name': 'tony', 'age': 20}
# setdefault
# dic = {"name": "tony"}
# dic.setdefault("name", "zzw") # name存在不处理
# dic.setdefault("gender", "男") # gender不存在添加进去
# print(dic) # {'name': 'tony', 'gender': '男'}
# pop(),popitem()
# dic = {"name": "tony", 'age': 20, "gender": "男"}
# print(dic.popitem()) # ('gender', '男')
# print(dic.pop("age")) # 20
# clear()
# dic = {"name": "tony", 'age': 20, "gender": "男"}
# dic.clear()
# print(dic) # {}
# get()
# dic = {"name": "tony", 'age': 20, "gender": "男"}
# print(dic.get("name")) # tony
# 区别 当指定的key在字典中不存在时
# print(dic.get("name1")) # None
# print(dic["name1"]) # 报错
# keys(),values(),items()
# dic = {"name": "tony", 'age': 20, "gender": "男"}
# print(dic.keys()) # dict_keys(['name', 'age', 'gender'])
# print(dic.values()) # dict_values(['tony', 20, '男'])
# print(dic.items()) # dict_items([('name', 'tony'), ('age', 20), ('gender', '男')])
# 取长度
# dic = {"name": "tony", 'age': 20, "gender": "男"}
# print(len(dic)) # 3
# 遍历
dic = {"name": "tony", 'age': 20, "gender": "男"}
# 取键
# for i in dic:
# print(i)
"""
name
age
gender
"""
# for i in dic.keys():
# print(i)
"""
name
age
gender
"""
# 取值
# for i in dic.values():
# print(i)
"""
tony
20
男
"""
# 取键值对
# for i in dic.items():
# print(i)
"""
('name', 'tony')
('age', 20)
('gender', '男')
"""
# for k, v in dic.items():
# print(k, v)
"""
name tony
age 20
gender 男
"""
# 判断字典是否有这个键
dic = {"name": "tony", 'age': 20, "gender": "男"}
print("name" in dic) # True
print("name" not in dic) # False