首页 > 代码库 > 字典方法

字典方法

1.字典
user = {"name": "cos", "age": 18, "sex": "Man"}
# 索引
# print (user["name"])
# 字典不能分片
# 循环,默认输出key
for i in user:
print (i)
  # 删除
del user["name"]
print (user)


2.
clear 清除字典中所有的项
  user = {"name": "cos", "age": 18, "sex": "Man"}
user.clear()
print (user)

3.
get 根据Key获取值
  user = {"name": "cos", "age": 18, "sex": "Man"}
print (user.get("age"))

4.
has_key 检查字典中是否有特定的键 (ps:在python3.0以后没有has_key)
  user = {"name": "cos", "age": 18, "sex": "Man"}
print (user.has_key("age"))

5.
keys、values、items
  user = {"name": "cos", "age": 18, "sex": "Man"}
# 获取键Key
print (user.keys())
# 获取值
print (user.values())
#获取键值
print (user.items())

6.
pop 获取给定Key的值,然后将这个键值删除
  user = {"name": "cos", "age": 18, "sex": "Man"}
print (user.pop("name"))
print (user)

7.
popitem 随机获取字典的键值,并删除它
  user = {"name": "cos", "age": 18, "sex": "Man"}
print (user.popitem())
print (user)

8.update 利用一个字典更新另一个字典,若Key键相同,则直接覆盖,不同就添加

user = {"name": "cos", "age": 18, "sex": "Man"}

n = {"name": "sin"}
user.update(n)
print (user)






字典方法