首页 » Python » 小象学院大数据分析集训营试听知识点整理-字典

小象学院大数据分析集训营试听知识点整理-字典

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
dict1 = {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}
dict1["key1"] = "value-1"
print(dict1)  # {'key1': 'value-1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
dict2 = {"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key4":"value-4"}
print(dict2["key4"])
print(len(dict1),len(dict2))  # 查看键值对数量

del dict1["key3"]
print(dict1)  # {'key1': 'value-1', 'key2': 'value2', 'key4': 'value4'},如果删除不存在的会报错
# 防止异常可以用in判断
if "key3" in dict1:
    del dict1["key3"]
    print(dict1)
else:
    print("key3不存在")

# get获取
print(dict1.get("key2"))  # value2
print(dict1.get("key3"))  # 不存在返回的None,因为日常中也有使用none作为值的,所以建议变成默认值
print(dict1.get("key3","N/A"))  # N/A

# for遍历
for key in dict1.keys():
    print(key+":"+dict1[key])
    print("{}:{}".format(key,dict1[key]))  # 格式化输出更方便且容易理解
'''
key1:value-1
key2:value2
key4:value4
'''

for value in dict2.values():
    print(value)

for item in dict1.items():
    print(item)
    print(type(item))  # tuple 元组
    print(item[0])  # 这个是key的值
    print(item[1])  # 这个是value的值

for k,v in dict2.items():
    print("{}:{}".format(k,v))
'''
key1:value1
key2:value2
key3:value3
key4:value-4
'''

dict1.clear()
print(dict1)  # {} 空字典

原文链接:小象学院大数据分析集训营试听知识点整理-字典,转载请注明来源!

0