Access Python dictionary (dict) of elements

 

Several ways to access elements in python dictionary

 

A: The "key-value pair" (key-value) visit:

 print(dict[key])

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
print(dict['D'])

输出:
ee

 

dict.get (key, [default]): default is optional, when used to specify a default return value does not exist 'key' if omitted, the default return None

. 1 = {dict:. 1, 2: ' AA ' , ' D ' : ' EE ' , ' Ty ' : 45 }
 Print (dict.get ( 2) )
 Print (dict.get (. 3 ))
 Print (dict.get (4, [ ' elemental key does not exist in the dictionary as ' ])) 

output: 
AA 
None 
[ ' not in the dictionary for the key element 4 ' ]

 

II: traversing the dictionary:

1. dictionary objects dict.items () method to get the individual elements of the dictionary i.e. "key on the" list of tuples:

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
for item in dict.items():
    print(item)

输出:
(1, 1)
(2, 'aa')
('D', 'ee')
('Ty', 45)

 

2. DETAILED acquired values ​​and each key:

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
for key, value in dict.items():
    print(key, value)

输出:
1 1
2 aa
D ee
Ty 45

 

3. The key and can also obtain a list of values ​​using a dictionary keys () and values ​​() Method:

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
for key in dict.keys():
    print(key)
for value in dict.values(): print(value) 输出: 1 2 D Ty
1 aa ee 45

 

Guess you like

Origin www.cnblogs.com/xioawu-blog/p/11074887.html