python: Getting Started book learning into practice (iv)

Chapter 6

  A dictionary is a series of key - value pairs. Each key is associated with a value, the key may be used to access the value associated therewith. In Python, the dictionary used in braces {}.

 

# Between the key and value separated by a colon, and the bond - between value pairs separated by a comma. 
alien_0 = { ' Color ' : ' Green ' , ' Points ' :. 5 }
 # value to obtain the associated key, the specified dictionary name and placed bonds in square brackets 
alien_0 = { ' Color ' : ' Green ' } 
 Print ( alien_0 [ ' Color ' ])
 '' ' 
Green 
' ''

 

  Dictionary create, add, modify, delete

# Create a dictionary 
test_dict = {}
 # Add 
test_dict [ ' test1 ' ] = ' in test_value ' 
test_dict [ ' test2 ' ] = ' in test_value ' 
test_dict [ ' Test3 ' ] = ' in test_value ' 
Print (test_dict)
 # modify 
test_dict [ ' test2 ' ] = ' test_value2 '
Print (test_dict)
 # delete 
del test_dict [ 'test3']
print(test_dict)
'''
{'test1': 'test_value', 'test2': 'test_value', 'test3': 'test_value'}
{'test1': 'test_value', 'test2': 'test_value2', 'test3': 'test_value'}
{'test1': 'test_value', 'test2': 'test_value2'}
'''

  Dictionary traversal:

'' ' 
To be prepared for traversing a dictionary for loop, two variables may declare, for storing the key - key and value pair. 
.Items name dictionary () returns a list of keys 
' '' 
test_dict = {} 
test_dict [ ' test1 ' ] = ' in test_value ' 
test_dict [ ' test2 ' ] = ' in test_value ' 
test_dict [ ' Test3 ' ] = ' in test_value ' 
for Key , value in test_dict.items ():
     Print (Key, value) 

for Key in test_dict:   
    (key)

for key in test_dict.keys():
    print(key)

for value in test_dict.values():
    print(value)

  Nesting: Sometimes, you need to store a series of dictionaries in the list, or the list as the value stored in the dictionary, which is called embedded nested sets. You can nest dictionary in the list, nested list in a dictionary even nested dictionaries in the dictionary.

 

Guess you like

Origin www.cnblogs.com/lizhihoublog/p/12576790.html