The dictionary is the Key-value data type
Create
info = { " stu01 " : " jack " Span style= "COLOR: #000000", " stu02 ": " Mike " ' < span>
View Code
Features of the dictionary:
- Dict is disordered.
- Key must be unique and inherently heavy
Increase
>>>info[' stu05 ' = ' kit ' #自动创建 {' stu01 ': ' Jack ', ' stu02 ': ' Mike ', ' stu03 ': ' Jay ', ' stu05 ', ' kit '}
By deleting
>>> Info.pop ("stu03") #标准删除, you must add the parameter {' stu01 ': ' Jack ', ' stu02 ': ' Mike '}
>>> del info[' stu03 ' #通用删除 {' stu01 ': ' Jack ', ' stu02 ': ' Mike '}
>>> Info.popitem () #随机删除 {' stu01 ': ' Jack ', ' stu03 ': ' Jay '}
Change
>>>info[' stu02 ' = ' bob '
{' stu01 ': ' Jack ', ' stu02 ': ' Bob ', ' stu03 ': ' Jay '}
Check
>>> ' stu02 ' in info #标准用法True >>> info.get (' stu02 ') #获取 ' Mike ' >>> info["stu1105"] # If a key does not exist, an error, get will not, does not exist only return Nonetraceback (most recent call last): File "<stdin>", line 1, in <module> Keyerror: ' stu1105 '
Multi-level dictionary nesting and manipulation
City = {' Asia ': {' China ': [' Beijing ', ' Shanghai ', ' Guangzhou '], ' Russia ': [' Moscow ', ' St Petersburg '], ' Japan ': [' Tokyo ', ' Nagoya ', ' Osaka '] }, ' Europe ': { ' uk ': [' London ', ' Birmingham '] }, ' Oceania ': { ' Australia ': [' Sydney ', ' Canberra '} }
city[Asia] [China][2]= ' Shenzhen ' #将广州改成深圳
#values
>>> info.values ()
[' Jack ', ' Mike ', ' Jay ']
#keys
>>> Info.keys ()
[' stu01 ', ' stu02 ', ' stu03 ']
#setdefault #键值存在则罢, there is no increase in
>>> info.setdefault (' stu06 ', ' Jane ')
{' stu01 ': ' Jack ', ' stu02 ': ' Mike ', ' stu03 ': ' Jay ', ' stu06 ', ' Jane '}
>>> info.setdefault (' stu02 ', ' Jane ')
{' stu01 ': ' Jack ', ' stu02 ': ' Mike ', ' stu03 ': ' Jay '}
#update #合并字典, if the key value is repeated, overwrite
>>> B = {1:2,3:4, ' stu01 ': ' Kit '}
>>> info.update (b)
{' stu01 ': ' Kit ', ' stu02 ': ' Mike ', ' stu03 ': ' Jay ', 1:2,3:4}
#items #字典转列表, it's ganso.
>>>info.items ()
[(' Stu01 ': ' Jack '), (' stu02 ': ' Mike '), (' stu03 ': ' Jay ')]
#通过一个列表生成默认dict
>>> ([Dict.fromkeys], ' testd ')
{1: ' Testd ', 2: ' Testd ', 3: ' TESTD '}
>>>c=dict.fromkeys ([1,2,3],[' Jack ', ' Sandra '])
>>>c[2][1]= ' Happy ' #全改了
{1:[' Jack ', ' Happy '],3:[' Jack ', ' Happy '],3:[' Jack ', ' happy '}
Loops
# Method 1in info: #高效 print(Key,info[key])# Method 2#print (Key,value)
"Python3" dictionary