I have below list of dictionary. I want to get an ordered dictionary on the basis of server_resource_name. I followed How to correctly sort a string with a number inside? but I wonder if there is something more pythonic?
ls = [
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i10_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i11_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i7_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i8_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i9_instance"
}
]
I am looking for output to be like below
ls = [
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i7_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i8_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i9_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i10_instance"
},
{
"flavor": "m1.small",
"internal_network_name": "inner-net",
"key_name": "tmp_key",
"server_resource_name": "i11_instance"
}
]
What I tried
test1 = []
for i in ls:
i['server_resource_name']
test1.append(i['server_resource_name'])
import re
def natural_key(string_):
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]
This gives me the sorted result in test2. How do I get the ls
now to be in sorted fashion?
print("-->", sorted(test1, key=natural_key))
Thats works maybe there are better way to do it
# Thats for parse number of instance
# print(int(re.findall(r'\d+', ls[0]["server_resource_name"])[0]))
sorted_ls = sorted(ls, key=lambda x: int(re.findall(r'\d+', x["server_resource_name"])[0]))
print(sorted_ls)