1. setdefault使用
dic1 = {'name': 'lucy', 'age': 18}
dic1.setdefault('age', 45)
dic1.setdefault('sex', '男')
2. pop使用
dic2 = {'name': 'lucy', 'age': 18}
ret2 = dic2.pop('age')
print(ret2)
print(dic2)
dic3 = {'name': 'lucy', 'age': 18}
ret3 = dic3.pop('sex', '没有此键')
print(ret3)
print(dic3)
3. clear使用
dic4 = {'name': 'lucy', 'age': 18}
dic4.clear()
print(dic4)
4. get使用
dic5 = {'name': 'lucy', 'age': 18, 'hobby_list': ['study', 'play', 'shopping']}
l1 = dic5.get('hobby_list')
print(l1)
l2 = dic5.get('sex')
print(l2)
l3 = dic5.get('sex', '没有此键')
print(l3)
5. keys()使用
dic6 = {'name': 'lucy', 'age': 18, 'hobby_list': ['study', 'play', 'shopping']}
print(dic6.keys(), type(dic6.keys()))
l1 = list(dic6.keys())
print(l1)
for k in dic6.keys():
print(k, end=',')
for k in dic6:
print(k, end=',')
6. values()使用
dic7 = {'name': 'lucy', 'age': 18, 'hobby_list': ['study', 'play', 'shopping']}
print(dic7.values())
print(list(dic7.values()))
for val in dic7.values():
print(val, end=',')
7. items()使用
dic8 = {'name': 'lucy', 'age': 18, 'hobby_list': ['study', 'play', 'shopping']}
print(dic8.items())
for it in dic8.items():
print(it)
for key, value in dic8.items():
print(key, value)
8. update()使用
dic9 = {'name': 'lucy', 'age': 18}
dic9.update(hobby='运动', hight=178)
print(dic9)
dic10 = {'name': 'lucy', 'age': 18}
dic10.update([('hobby', '运动'), ('hight', 178)])
print(dic10)
dic11 = {'name': 'lucy', 'age': 18}
dic12 = {'name': 'tom', 'hight': 178}
dic11.update(dic12)
print(dic11)
dic13 = {'name': 'lucy', 'age': 18}
dic13.update(name='tom')
print(dic13)
9. fromkeys()使用
dict14 = dict.fromkeys(['k1', 'k2', 'k3'])
print(dict14)
dict14 = dict.fromkeys(['k1', 'k2', 'k3'], 'value')
print(dict14)
10. copy使用
dict15 = dict(one=1, two=2, three=3)
dict16 = dict15.copy()
print(dict16)
11. popitem()使用
dict17 = dict(one=1, two=2, three=3)
a = dict17.popitem()
print(a)
print(dict17)