python基础语法-python三大内建数据结构之字典(dict)
程序员文章站
2022-03-03 10:27:35
...
字典(dict):一组无序的组合数据,以键值对形式出现。
1.创建
# 1
dict1 = {}
# 2
dict1 = {"one": 1, "two": 2, "three": 3}
2.访问
dict1 = {"one": 1, "two": 2, "three": 3}
print(dict1["one"])
dict1["one"] = 4
print(dict1["one"])
成员检测只检测key。其他类似于list。
3.遍历
dict1 = {"one": 1, "two": 2, "three": 3}
for k in dict1:
print(k, dict1[k])
for k in dict1.keys():
print(k, dict1[k])
for v in dict1.values():
print(v)
for k, v in dict1.items():
print(k, v)
4.字典生成方式
dict1 = {"one": 1, "two": 2, "three": 3}
dict2 = {k: v for k, v in dict1.items() if v % 2 == 0}
print(dict2)
clear等同list。
5.get用法
dict1 = {"one": 1, "two": 2, "three": 3}
print(dict1.get("one"))
print(dict1.get("four",4))