-3

I have a list of dictionaries in python, called all_data. The structure of each dict object hold by all_data is:

{
    'href': u'http://malc0de.com/database/index.php?search=c.img001.com', 
    'type': u'text/html', 
    'rel': u'alternate',
    'title': u'c.img001.com', 
    'summary': u'URL: c.img001.com/re58/girlshow_20300025849.exe, IP Address: 14.215.74.85, Country: CN, ASN: 58543, MD5: 31d5f481153ccd2829558720f8d90d81', 
    'title_detail': {
        'base': u'http://malc0de.com/rss/', 
        'type': u'text/plain', 
        'value': u'c.img001.com', 
        'language': None
     }
}

I want to perform sorting base on the name of 'Country' which is present as sub-string to the value of 'summary' key. The content of string is like:

u'URL: c.img001.com/re58/girlshow_20300025849.exe, IP Address: 14.215.74.85, Country: CN, ASN: 58543, MD5: 31d5f481153ccd2829558720f8d90d81', 

I want to sort the list of dicts based on the Country name in the alphabetical order.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
jeff_h
  • 519
  • 1
  • 9
  • 26

1 Answers1

2

Since the value 'Country' on which you want to sort is present as the part of string in the key 'summary'; you have to firstly extract the value of 'Country' in order to perform the sorting.

One way is to create the function to convert the str to dict as:

def get_dict_from_str(my_str):
    return dict(item.split(': ') for item in my_str.split(', '))

Then use this function along with lambda function with sorted() as:

sorted_list = sorted(dict_list, key=lambda x: get_dict_from_str(x['summary'])['Country'])

where dict_list is list of dictionaries holding the dicts of format as is mentioned in the question.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126