python字典

python中的字典是用花括号包裹的唯一内键映射的数据类型

1、字典的内置函数

#字典(3.6以上版本有序)
dic1={"name":"huahua","age":23,"gender":"male"}

#增改update,有则修改,无则添加
dic2={"name":"yuanyuan"}
dic1.update(dic2)
print(dic1)
"""
执行结果:
{'name': 'yuanyuan', 'age': 23, 'gender': 'male'}
"""

dic3={"score":100}
dic1.update(dic3)
print(dic1)

"""
执行结果:
{'name': 'yuanyuan', 'age': 23, 'gender': 'male', 'score': 100}
"""


#获取数据 取不到返回默认值
print(dic1.get("name",None))

#setdefault取字典的值,取不到则设置默认值
dic1.setdefault("love","football")
print(dic1)#{'name': 'yuanyuan', 'age': 23, 'gender': 'male', 'score': 100, 'love': 'football'}

#for循环

for k,v in dic1.items():
    print(k,v)

"""
执行结果:
name yuanyuan
age 23
gender male
score 100
"""
print(dic1.keys())#dict_keys(['name', 'age', 'gender', 'score'])
print(dic1.values())#dict_values(['yuanyuan', 23, 'male', 100])
print(dic1.items())#dict_items([('name', 'yuanyuan'), ('age', 23), ('gender', 'male'), ('score', 100)])

#pop删除指定键值对 popitem 删除最后一个键值对 clear清空列表
dic1.pop("name")
print(dic1)
dic1.popitem()
print(dic1)
dic1.clear()
print(dic1)

"""
执行结果:
{'age': 23, 'gender': 'male', 'score': 100, 'love': 'football'}
{'age': 23, 'gender': 'male', 'score': 100}
{}
"""

2、字典生成式

{字典内容+循环条件+判断条件}

dic={"name":"tiantian","age":23,"love":"football"}
dic2={v:k for k,v in dic.items() if v==23}
print(dic2)#{23: 'age'}

上一篇:研一上过半总结(2021.9.23——2021.12.6)


下一篇:23种设计模式分类