Python sorts instances of dictionaries

  • 2020-04-02 14:07:03
  • OfStack

This article illustrates how python sorts dictionaries, which is a useful technique. Share with you for your reference.

The specific implementation method is as follows:


import itertools 
thekeys = ['b','a','c'] 
thevalues = ['bbb','aaa','cccc'] 
 
d = dict(itertools.izip(thekeys,thevalues)) # Create a dictionary  
print d 
 
def sortedDictValue(adict): 
  keys = adict.keys() 
  keys.sort() 
  return map(adict.get,keys) 
 
print sortedDictValue(d)
import itertools
thekeys = ['b','a','c']
thevalues = ['bbb','aaa','cccc']
def sortedDictValue(adict): # Custom sort function , Get the dictionary first keys() And then to keys sorting , And then finally in order keys Take the value of the dictionary  
  keys = adict.keys() 
  keys.sort() 
  return map(adict.get,keys)# The only difference here is that it calls the built-in map Delta function, for each of these keys The project in, call adict.get Function, returns a list  
 
print sortedDictValue(d) 
# Print out the same result  

The running result of the program is:


{'a': 'aaa', 'c': 'cccc', 'b': 'bbb'}
['aaa', 'bbb', 'cccc']
['aaa', 'bbb', 'cccc']

I hope that this article has helped you to learn Python programming.


Related articles: