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 StackOverflow 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)
PS: I appeal to you. Please do not judge this question. I am a beginner, not even my first year at college, i have little experience in Python and i'm learning. So only comment if you're really willing to help. Thank you
Thank you, and sorry if this question seems really stupid. I am really trying