字典类似列表,列表使用’’索引-数据”的形式存储数据,字典使用键值对的形式存储数据
列表只能存储一种数据类型,而且索引固定
字典的“键”和“值”可以是任意类型,这里的“键”相当于列表的索引
列表在内存的数据是有序的,字典是无序的
1 2 3 4 5 6 7 8 9 10
| stu1 = { "name":"manu","age":19,"gender":"male" }
stu1["hobby"] = "coding"
print(stu1["name"])
stu1["age"] = 20
del stu1["gender"]
|
字典与列表的嵌套
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| stu = [{ "name":"manu","age":19,"gender":"male" }, { "name":"manu","age":19,"gender":"male" }, { "name":"后排","age":19,"gender":"male" }, { "name":"sb1号","age":19,"gender":"male" }, { "name":"sb2号","age":19,"gender":"male" }]
print(stu[2]["name"])
stu2 = { "name":"manu", "age":19,"gender":"male", "hobby":["programing","coding"]} print(stu2["hobby"][1])
|
判断是否相等
- 列表是有顺序的,判断时顺序不对也就不相等
- 字典是无序的,键和值对等则就相等
遍历
键
1 2 3 4 5 6 7 8
| for i in dict1.keys(): print(i)
print(dict1.keys)
keys = list(dict1.keys) print(keys)
|
值
1 2 3 4 5 6 7 8
| for i in dict1.values(): print(i)
print(dict1.values)
values = list(dict1.values) print(values)
|
键值对
1 2 3 4 5 6 7 8 9 10
| for i in dict1.items(): print(i) print(i[0],i[1])
for k,v in dict1.items(): print(k,v)
|
判断是否存在
1 2 3 4 5 6
| "test" in dict1.values()
"test" in dict1.keys()
"test" in dict1
|
默认值
一般情况下使用字典都不会知道里面的数据,可以设置一个默认值
1 2
| dict1.setdefault("key","value")
|