I. Ordering of dictionary elements
Dict.keys (), Dict.values (), Dict.items ()
It's a good idea to sort by combining Max, Min, sorted,zip , and also note how the dictionary lambda operation does not use zip :
Price = { ' a ': 1, ' B ': 2, ' C ': 3}# The value of multiple keys simultaneously takes the form of a tuple comparison, in practical application Note min_p = min (Zip (price.values (), Price.keys ())) max_p = max (Zip (price.values (), Price.keys ())) print (Min_p, max_p) # (1, ' A ') (3, ' C ') # The dictionary is processed when the key is processed, It is difficult to understand Max (price, Key=lambda k:price[k]) # ' C ' # sort operation sorted (Zip (price.values (), Price.keys ()), Key=lambda x: not using zip -x[0]) # [(3, ' C '), (2, ' B '), (1, ' a ')]
Ii. Dictionaries and collections
A dictionary is a mapping between a set of keys and a collection of values. The keys () method of the dictionary returns a key-View object that represents a collection of keys. A rare feature of the key view is that they also support collection operations, such as set merging, intersection, and difference operations. So, if you want to perform some normal collection operations on the keys of the collection, you can use the key view objects directly without first converting them to a set.
The dictionary's items () method returns an element view object that contains (key, value) pairs. This object also supports collection operations and can be used to find out which two dictionaries have the same key-value pairs.
Although the values () method of the dictionary is similar, it does not support the collection operations described here. In part because the value view does not guarantee that all values are different, this can cause problems with some collection operations. However, if you are trying to perform these set operations on a value, you can first convert the value collection to set and then perform the set operation.
A = { ' x ': 1, ' y ': 2, ' z ': 3}b = { ' W ': 4, ' x ': 5, ' y ': 6}# dictionary. Items () returns the actual collection print (A.items () & B.items ()) # Set () print (A.items ()-B.items ()) # {(' Z ', 3), (' X ', 1), (' Y ', 2)}# dictionary. Keys () returns the actual collection print (A.K Eys ()-B.keys ()) # {' Z '}# because there may be duplicate elements, so. VALUES () is not a collection # print (A.values ()-B.values ()) # Error
"Python coolbook" Data Structures and Algorithms _ Dictionary comparison & Dictionaries and collections