简体   繁体   中英

python sorting deep in objects

I need some help with sorting in python. I got a data object, in this objects are lists and I like to sort the data for a specific list item. Currently I print it out like this:

 for item in data:
     for proj in item:
         print proj.get('id')

So I want this data already sorted by the 'id' item.

This is how the data object looks like, if I print it:

[[{u'archived': False, u'name': u'someone', u'num_files': 0, u'managed_by': {u'username': u'somebody', u'role': u'somerole', u'email_address': u'me@somewhere', u'id': u'307', u'name': u'firstname lastname'}, u'updated_on': u'2015-06-18 17:55:39', u'id': 23}, 
{u'archived': False, u'name': u'someoneelse', u'num_files': 0, u'managed_by': {u'username': u'somebody else', u'role': u'somerole', u'email_address': u'you@somewhere', u'id': u'341', u'name': u'Firstname Lastname'}, u'updated_on': u'2015-06-09 17:38:52', u'id': 48}]]

Just two lists from the whole, but I like to sort for the last id, in this example 23 and 48

Try this:

import numpy as np
data_new = np.array(data).flatten()
sorted_list = sorted(data_new, key=lambda x: x['id'])

First line will create one list of dict. Second will sort them by 'id' key. After that you could print it like you want:

for i in sorted_list:
    print(i['id'])

Edit: Because your list could contain sublists of different sizes (like here ) this will broke ndarray.flatten or numpy.ravel, also because your elements are dictionaries np.fromiter will unworkable too. So you should change second line to this:

data_new = np.hstack(data)

I did a mistake, I used .append with my list to add more entries, instead I should have used .extend Now my list is not that deep anymore and it's all way much easier:

sorted_list = sorted(data, key=lambda x: x['id'])
for item in sorted_list:
    print str(item.get('id')) + " : " + item.get('name')

But thanks for the numpy tip, I think that would be helpful if I reall would search deeper in the objects sublist etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM