English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example of Traversing and Sorting Dictionary in Python

This article describes the implementation of dictionary traversal and sorting in Python. Shared for everyone's reference, as follows:

Dictionary Traversal:

First:

items():

Function: Returns the dictionary key-value pairs in the form of a list

eg:

dict_={"a":2,"b":3,"c":6}
dict_.items()
>>>[('a',2),('b',3),('c',6)]

iteritems():

Function: Return dictionary key-value pairs as an iterator object

# -*- coding: cp936 -*-
dict1={'a':1,'b':2,'c':3}
#The first method:
for d in dict1:
  print "%s:%d"%(d,dict1[d])
print
#The second method:
for k,v in dict1.items():
  print "%s:%d"%(k,v)
print
#The third method:
for k,v in dict1.iteritems():
  print "%s:%d"%(k,v)
print
#The fourth method:
for k in dict1.iterkeys():
  print "%s:%d"%(k,dict1[k]
print
#Fifth:
for v in dict1.itervalues():
  print v
print
#Sixth:
for k,v in zip(dict1.iterkeys(),dict1.itervalues()):
  print "%s:%d"%(k,v)
print

The zip() function can merge lists and create a list of tuple pairs.

eg:

list1=[1,2,3]
list2=[4,5,6]
zip(a,b)
>>>[(1,4,(2,5,(3,6)]

The zip() function can take any type of sequence, and can also take more than two parameters. When the length of the input parameters is different, zip automatically takes the length of the shortest sequence as the standard for truncation, and obtains a tuple.

Dictionary sorting:

First:

Process: The first parameter is passed to the second parameter "key"

The second parameter extracts the key [0] or value [-Key-value1]

dic is the comparison function, value is the sorting object (key or value)

reverse indicates ascending or descending order, the value has true-Descending and false-Ascending (default value)

eg: Sort dictionary items by key value (put dict[1] can be replaced with dict[0] to sort by dictionary keys)

sorted(dict.iteritems(), key=lambda dict:dict[1],reverse=True)

Explanation:

dict.iteritems() gets a list of [(key, value), (key, value), (key, value)...]. Then use the sorted method, specify the sorting by key value through the key parameter, that is, the first element d[1].values() to sort. reverse=True means to reverse (i.e., descending order), the default is ascending order.

The lambda function and the function iteritems()

lambda:

Function: Create an anonymous function

eg:

fun_1=lambda a:a+1
print fun_1(1)
>>>2
fun_2=lambda a,b:a+2*b
fun_2(1,1)
>>>3

iteritems():

Function: Return dictionary key-value pairs as an iterator object

# -*- coding: cp936 -*-
print "Sort dictionary items by key value"
dict1={'a':3,'c':1,'b':2}
#Ascending order:
dict_a=sorted(dict1.iteritems(),key=lambda dict1:dict1[1],reverse=False) 
#Descending order sorting reverse=True, this parameter can be omitted, the default is False. Or dict_a.reverse()
print dict_a, "\n"
#Descending order:
dict2={'a':3,'c':1,'b':2}
dict_b=sorted(dict2.iteritems(),key=lambda dict2:dict2[1],reverse=True)
print dict_b, "\n"
##############################################################
print "Sort by dictionary key"
dict3={'d':6,'e':5,'f':4}
#Descending order:
dict_c=sorted(dict3.iteritems(),key=lambda dict3:dict3[0],reverse=True) 
#Descending order sorting reverse=True, this parameter can be omitted, the default is False. Or dict_a.reverse()
print dict_c, "\n" 
#Ascending order:
dict4={'d':6,'e':5,'f':4}
dict_d=sorted(dict4.iteritems(),key=lambda dict4:dict4[0])#Change to descending order in the same way as above
print dict_d, "\n"

PS: Here is another sorting demonstration tool for everyone to refer to:

Online Animation Demonstration of Insertion/Selection/Bubble/Merge/Shell/Quick Sort Algorithm Process Tool:
http://tools.jb51.net/aideddesign/paixu_ys

Readers who are interested in more content related to Python can check the special topics on this site: 'Python Data Structures and Algorithms Tutorial', 'Python Encryption and Decryption Algorithm and Technique Summary', 'Python Coding Operation Technique Summary', 'Python Function Usage Technique Summary', 'Python String Operation Technique Summary', and 'Python入门与进阶经典教程'.

I hope the content described in this article will be helpful to everyone in Python program design.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like