Dictionary data type ---

Create dictionary

dict = { 
'role 1': 'Suminoe Azure',
'role' 2 ':' Ultimately ',
' role 3 '' inu our '
}
print (dict)

Add elements

dict = {
'role 1':'abeno seme',
'role 2':'kagela',
'role 3':'inu kami'
}
print(dict)

dict['role 4'] = '大天狗'

print(dict)

Removing elements

Use pop () method

dict = {
'role 1':'abeno seme',
'role 2':'kagela',
'role 3':'inu kami'
}
print(dict)

dict.pop('role 1')#标准方法

print(dict)

Use del

dict = {
'role 1':'abeno seme',
'role 2':'kagela',
'role 3':'inu kami'
}
print(dict)

del dict['role 2']

print(dict)

Use popitem () method

 

= {dict 
'Role. 1': 'Abeno Seme',
'Role 2': 'kagela',
'Role. 3': 'INU Kami'
}
print (dict)

dict.popitem () # randomly deleted, additional parameters can not

print ( dict)

Modify elements

dict = {
'role 1':'abeno seme',
'role 2':'kagela',
'role 3':'inu kami'
}
print(dict)

dict['role 3'] = "犬神"

print(dict)

View element

dict = { 
'Role. 1': 'Abeno Seme',
'Role 2': 'kagela',
'Role. 3': 'INU Kami'
}

Print ( 'Role. 1' in dict) # standard usage, key 'role 1' whether there exists returns True, there is no return Fales
Print (dict.get ( 'Role. 1')) # is not given, there is a return value, there is no return None
# and get () different
print (dict [ 'role 3' ]) # return value exists
print (dict [ 'role 4' ]) # error does not exist

Multi-level dictionary

= {the MENU 
"barbecue": {
"beef": [ "cow streaky", "cow rib"],
"lamb": [ "Kebab", "big fat kidneys"],
"fish": [ "grilled salmon head "," roast saury "]
},
" sushi ": {
" sushi ": [" salmon sushi "," tuna sushi "],
" sushi ship ": [" salmon ship "," ship tuna " ],
"sashimi": [ "sashimi tuna", "red shell sashimi"]
},
"beverage": {
"wine": [ "Bordeaux", "Cabernet Sauvignon"],
"beer": [ "Asahi", "Kirin"],
"sake": [ "The pine", "burning taro"]
}
}

other

= {dict 
'Role. 1': 'Abeno Seme',
'Role 2': 'kagela',
'Role. 3': 'INU Kami'
}
# print value
Print (dict.values ())

# print key
print (dict. Keys ())

#setdefault: have return value, put the value of the parameter is not set to the default
dict.setdefault ( 'role 4', 'vampire Ji')
Print (dict)
dict.setdefault ( 'Role 2', 'God Le ')
Print (dict)

#update
Print (dict)
B = {. 1: 2,3:. 4, "Role 2": "Kagura"}
dict.update (B)
Print (dict)

#items dictionary to convert a collection of
print (dict.items ())

Circulation dictionary

method 1

dict = {
'role 1':'abeno seme',
'role 2':'kagela',
'role 3':'inu kami'
}

for i in dict:
print(i,dict[i])

Method 2

 

= {dict 
'Role. 1': 'Abeno Seme',
'Role 2': 'kagela',
'Role. 3': 'INU Kami'
}

for K, V in dict.items (): first dictionary into a list # when large amount of data, inefficient
print (k, v)

Guess you like

Origin www.cnblogs.com/goldtree358/p/11611037.html