-2

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
qwerty
  • 670
  • 5
  • 10
  • 20
  • 3
    Strings sort in lexicographical order, so e.g. `"21" < "3"`. See e.g. http://stackoverflow.com/q/5967500/3001761 – jonrsharpe Nov 03 '14 at 12:35
  • You could also avoid copying altogether by doing `for key in sorted(static_mac_dict.keys(), key=int): print static_mac_dict[key]` – Hannes Ovrén Nov 03 '14 at 12:39

3 Answers3

3

The sort function is working properly - just not according to what you expected. It's sorting the strings in the lexicographic order of their characters.

Python (or any other language) can't possibly know that you really want to interpret the strings as numbers - unless you tell it (see gnibbler's answer).

Note that, as in most languages, sorting in python entirely depends on the type of the objects. Most built-in types (such as int, float, str, even tuple and list) have a well-defined ordering. Instances of custom classes don't have a (meaningful) order, but you can define it if you want.

loopbackbee
  • 21,962
  • 10
  • 62
  • 97
1

Since the keys are strings, they will be compared lexicographically instead of numerically as you desire.

you can sort them by using int as the key function

keysList.sort(key=int)

that will save you the explicit steps converting to int and back to str

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

As stated in the comment:

Strings sort in lexicographical order, so e.g. "21" < "3".

So hopefully that answer your question.

Now, if you want to convert a list of strings to a list of integers then take a look at this question: Convert all strings in a list to int.

Answer:

results = ['1294', '1518', '2230', '2273', '2844', '3642', '3971', '816']
results = map(int, results)
Community
  • 1
  • 1
idanshmu
  • 5,061
  • 6
  • 46
  • 92