I have a dictionary named "static_mac_dict" which has a key-value items as follows:
'2273': {'Type': 'Static', 'Port': 'Eth1/4', 'Mac Address': '80:9B:4B:D2:C8:E1'}
I would to sort the dictionary based on key, and then PRINT ONLY its values.
However, I can`t do that since dictionaries cannot be sorted.
Therefore, I decided to
- Copy all the dictionary keys to a list (named keysList).
- Sort the list by using Python`s list built in sort() function.
- Iterate the sorted keys list and then print the dictionary values.
keysList look like this:
['1294', '1518', '2230', '2273', '2844', '3642', '3971', '816']
Now to the code:
keysList = []
keysList = static_mac_dict.keys()
keysList.sort()
print (keysList)
for key in keysList:
if key != None:
print dictionary values...
HOWEVER, I noticed that in the above code, the keyslist is NOT sorted after using the sort() function.
The sort function does work properly, only IF I convert the keys from STR to INT as you can see in the code below:
keysList = []
keysList = static_mac_dict.keys()
for i in range(len(keysList)):
keysList[i] = int(keysList[i])
#sorting the list
keysList.sort()
print (keysList)
# converting the list items back to str
for i in range(len(keysList)):
keysList[i] = str(keysList[i])
for key in keysList:
if key != None:
print dictionary values...
My question is: Why do I need to convert the list item to INT so that sort function will work properly?
Thanks in advance.