#coding =utf8
#字典由键和对应的值组成 (Key-value pair)--hash table, dictionary element can also be empty
Dict1 = {' name ': ' Kaly ', ' age ': ' Sex ': ' Male '}
Dict2 = {}
#键与值间需用冒号隔开, each pair of keys requires a comma as a delimiter, and the relationship between the key and the value is one-to-many
Print Dict1
#字典是 are not sequential , they are randomly sorted when they are printed, and access to the dictionary elements is required by key
#>>>
#{' age ': ' Name ': ' kaly ', ' sex ': ' Male '}
Print dict1[' age ' #输出age对应的值: 20
#print dict1[' aaa '] #返回KeyError: ' AAA ', access to the dictionary does not exist key will be error
# Modify Add Dictionary element -- directly modify the value corresponding to the existing key/increase the non-existent key value pair
Dict1[' age '] = 18
dict1[' test ' = ' test '
Print Dict1 #{' test ': ' Test ', ' age ':, ' name ': ' kaly ', ' sex ': ' Male '}
#字典中 The same key appears more than once , by default only the value corresponding to the last key is taken
DICT3 = {' str ': ' haha ', ' str ': ' Hello ', ' str ': ' Test ', ' age ': 22}
Print dict3 #{' age ': $, ' str ': ' Test '}
#删除字典元素和字典
del dict3[' str '] #删除键位 ' str ' data
Print dict3 #{' age ': 22}
Del Dict2 #删除整个字典
#print dict2 #NameError: Name ' Dict2 ' is not defined
Dict3.clear () #清除dict3字典所有数据
Print Dict3 #{}
print '--------------------------------------'
#遍历字典元素-In the loop, the value of each key of the dict1 is extracted and given to the key variable.
For key in Dict1:
Print Dict1[key]
#字典常用的内置函数
Print CMP (DICT1,DICT3) #大于返回1, equal to return 0, less than return-1, key-by-button comparison
Print Len (dict1) #返回dict1字典键的总数: 4
Print str (dict1) #{' test ': ' Test ', ' age ': ', ' name ': ' kaly ', ' sex ': ' Male '}
Print type (dict1) #返回字典类型 <type ' dict ' >
Python Basics 9-dictionaries