Dictionary # In Python, the dictionary is a series of key-value pairs. # key-value pairs are separated by:, and key-value pairs are separated
Python learning dictionary of Guibs
# Dictionary # the dictionary in Python is a series of key-value pairs. # keys and values are separated by:, and key-value pairs are separated by: book_0 = {'name': 'Swift ', 'price': 22} book_1 = {'name ': 'python', 'price': 22} # access the value in the Dictionary # print (book_0.keys () of all keys in the Dictionary # print (book_0.values () of all values in the dictionary ()) # To obtain the value associated with the key, you can specify the dictionary name and the key print placed in square brackets in sequence (book_0 ['name'] + ': '+ str (book_0 ['price']) print (book_1 ['name'] + ":" + str (book_1 ['price']) # create an empty dictionary book_2 = {} print (book_2) # Add a key-value pair, you can specify the dictionary name, the key enclosed in square brackets, and the associated value book_2 ['author'] = 'gubis 'print (book_2) # Modify the values in the Dictionary # specify the dictionary name, the key enclosed in square brackets, and the updated value book_2 ['autor'] = "Guibs82" print (book_2) # delete a key-value pair # [del] del book_2 ['author'] print (book_2) # traverse the dictionary # [dictionary. items ()] user_0 = {'username': 'efermi', 'First ': 'enrico', 'la': 'fermi',} for key, value in user_0.items (): print ("Key:" + key) print ("Value:" + value) # traverse all keys in the Dictionary #[. keys ()] for key in user_0.keys (): print (". keys () "+ key +" and value is "+ user_0 [key]) for key in user_0: print (". keys () "+ key +" and value is "+ user_0 [key]) # traverse all keys in the dictionary in sequence # [sorted ()] for key in sorted (user_0.keys (): print ("Sorted key is" + key) # traverse all values in the dictionary for value in user_0.values (): print (value) # If the dictionary contains a large number of duplicate values, you can use the set # [set ()] favorite_ages = {'guibs ': 'Swift _ and_Python' to remove duplicate values ', 'guibs82 ': 'Swift _ and_Python', 'someone': 'Python'} for value in favorite_languages.values (): print ("Without set () value is" + value) for value in set (favorite_incluages.values (): print ("With set () value is" + value) # nesting # dictionaries and lists can be nested with each other # store dictionaries in the list books = [book_0, book_1, book_2] for book in books [: 1]: print (book) # Dictionary storage list pizza = {'name': 'B _ pizza', 'size': ['small', 'Big'], 'price': [10, 15],} print (pizza) # store the dictionary price = {'small': 20, 'Big ': 25,} pizza = {'name ': 'g _ pizza', 'size': ['small', 'Big '], 'price': price} print (Pizza)
The above is the content of the Python learning dictionary of Guibs. For more information, see The PHP Chinese website (www.php1.cn )!