1. Dictionary definition, key unique, value arbitrary
dic={key0:value0,key1:value1}
2. Output
print(dic[key0])>>:value0
3. Traversing a dictionary
3.1keys () traverse the key in the dictionary
dic={‘name‘:‘zhangsan‘,‘age‘:20}for k in dic.keys(): print(k)>>:nameage
3.2values () traverse the value in the dictionary
dic={‘name‘:‘zhangsan‘,‘age‘:20}for v in dic.values(): print(v)>>:zhangsan20
3.3items () traversing the key,value in the dictionary
dic={‘name‘:‘zhangsan‘,‘age‘:20}for k,v in dic.items(): print(k+‘:‘+str(v))>>:name:zhangsanage:20
4. Dictionary Insert Element
dic={‘name‘:‘zhangsan‘,‘age‘:20}dic[‘job‘]=‘python‘print(dic)>>:{‘name‘: ‘zhangsan‘, ‘age‘: 20, ‘job‘: ‘python‘}
5. Modify values by key
dic={‘name‘:‘zhangsan‘,‘age‘:20}dic[‘name‘]=‘lisi‘print(dic)>>:{‘name‘: ‘lisi‘, ‘age‘: 20}
6.pop () Remove elements from the dictionary
dic={‘name‘:‘zhangsan‘,‘age‘:20}dic.pop(‘name‘)print(dic)>>:{‘age‘: 20}
7. Interpret whether the element is in the dictionary:
dic={‘name‘:‘zhangsan‘,‘age‘:20}tmp=‘name‘if tmp in dic:#和 if tmp in dic.keys()相同: print("%s in dic" %tmp)#判断元组是否在值中if tmp in dic.values(): print("%s in dic" %tmp)
Python Basics-Dictionary (dictionary)