Python Multi-Dimensional List/Dict: Sort by field?

Question:

I am trying to generate a python list with some dictionaries and then sort the list by using a specific object in the dictionaries, inside the list.

I have the following code:

data = {"data": []}

for client in clients:
    if client["network"] == "wireless":
        if "hostname" in client:
            if client["hostname"][0:3] == "PA_" or client["hostname"][0:3] == "PA-":
                item = {"{#HOSTNAME}": client["hostname"], "{#IP}": client["ip"], "{#MAC}": client["mac"],
                        "{#UPTME}": client["_uptime_by_uap"]}
                data["data"].append(item)

pprint(data)

It outputs exactly:

{'data': [{'{#HOSTNAME}': 'PA_abc',
           '{#IP}': '192.168.1.1',
           '{#MAC}': 'xx:xx:xx:xx:xx:xx',
           '{#UPTME}': 540339},
          {'{#HOSTNAME}': 'PA-cxz',
           '{#IP}': '192.168.1.2',
           '{#MAC}': 'zz:zz:zz:zz:zz:zz',
           '{#UPTME}': 583768},
          {'{#HOSTNAME}': 'PA_jjj',
           '{#IP}': '192.168.1.3',
           '{#MAC}': 'cc:cc:cc:cc:cc:cc',
           '{#UPTME}': 1158902},
          {'{#HOSTNAME}': 'PA_BBB',
           '{#IP}': '192.168.1.4',
           '{#MAC}': 'ff:ff:ff:ff:ff:ff',
           '{#UPTME}': 1086962}]}

What i want to achieve is to print this list sorting by {#UPTME}…

I tried following a logic i found on this article regarding list sorting and came up with:

data.sort(key=lambda x: x.get('data'['{#UPTME}']))

But when i run it, i get the following error message:

AttributeError: 'dict' object has no attribute 'sort'

Also, i searched for this question here at Stack Overflow but saw multiple downvoted question, none of them solved for me. Before what I tried and the questions:

Question 1:
Tried changing from #1 to #2, same error happened:

data.sort(key=lambda x: x.get('data'['{#UPTME}'])) #1
input_list = sorted(data.iteritems(), key=lambda x: x[0]['{#UPTME}']) #2

Question 2: Tried 2 methods specified there, marked as solved, but did’nt work also:

# Method #1 Test
newlist = sorted(data, key=lambda x: x['{#UPTME}']) 
print(newlist)

# Method #2 Test
newlist2 = sorted(data, key=itemgetter('{#UPTME}')) 
print(newlist2)
Asked By: Raul Chiarella

||

Answers:

I think you just made a slight mistake in calling sort on the dictionary instead of the array inside the dictionary.

try:

data['data'].sort(key=lambda x: x.get('{#UPTME}'))
Answered By: Stackerexp

You can use Dict Comprehension and try like below if you have multiple keys and values in data and you want to sort value of each key.

data_new = {k: sorted(v, key=lambda x:x.get('{#UPTME}', float('inf'))) 
            for k,v in data.items()}
print(data_new)

{'data': [{'{#HOSTNAME}': 'PA_abc',
   '{#IP}': '192.168.1.1',
   '{#MAC}': 'xx:xx:xx:xx:xx:xx',
   '{#UPTME}': 540339},
  {'{#HOSTNAME}': 'PA-cxz',
   '{#IP}': '192.168.1.2',
   '{#MAC}': 'zz:zz:zz:zz:zz:zz',
   '{#UPTME}': 583768},
  {'{#HOSTNAME}': 'PA_BBB',
   '{#IP}': '192.168.1.4',
   '{#MAC}': 'ff:ff:ff:ff:ff:ff',
   '{#UPTME}': 1086962},
  {'{#HOSTNAME}': 'PA_jjj',
   '{#IP}': '192.168.1.3',
   '{#MAC}': 'cc:cc:cc:cc:cc:cc',
   '{#UPTME}': 1158902}]}
Answered By: I'mahdi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.