9.1 第一个例子
#!/usr/bin/python3
dict = {}
dict['haha'] = "hehe"
dict[2] = 3343
print (dict['haha'])
print (dict[2])
print (dict)
print (dict.keys())
print (dict.values())
结果:
hehe 3343 {'haha': 'hehe', 2: 3343} dict_keys(['haha', 2]) dict_values(['hehe', 3343])
9.2 获取字典元素个数
#!usr/bin/python3
d = {"1": "haha", "2": "hehe"}
print("len(d) = ", len(d))
结果:
len(d) = 2
9.3 获取字典的类型
#!usr/bin/python3
dicts = {"1":"haha","2":"ehhehe"}
print("type = ", type(dicts))
结果:
type = <class 'dict'>
9.4 删除字典的值
#!usr/bin/python3
dicts = {"1":"haha","2":"hehehe"}
print("before: ", dicts)
del dicts["1"]
print("after: ", dicts)
结果:
before: ?{'1': 'haha', '2': 'hehehe'} after: ?{'2': 'hehehe'}
9.5 清空字典
#!usr/bin/python3
dicts = {"1":"haha","2":"hehehe"}
print("before: ", dicts)
dicts.clear()
print("after: ", dicts)
结果:
before: ?{'1': 'haha', '2': 'hehehe'} after: ?{}
9.6 遍历字典
#!usr/bin/python3
dicts = {"1":"haha", "2":"hehe"}
for key in dicts.keys():
print(dicts[key])
print("=========================")
for value in dicts.values():
print(value)
print("=====================")
for key,value in dicts.items():
print(key + ": " + value)
结果:
haha hehe ========================= haha hehe ===================== 1: haha 2: hehe
|