5 Replies - 361 Views - Last Post: 16 April 2013 - 06:11 AM Rate Topic: -----

#1 donfanzu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 08-April 12

Ordering a list of dictionaries by key

Posted 05 April 2013 - 06:45 AM

Hi guy,

I'm trying to order my list by the key 'house_id'. The below implementation works perfectly and
the data is sorted.

data = [
    {"house_id": 'MCM/ALPR420/020     '},
    {"house_id": 'ROT/METR020/020     '},
    {"house_id": 'MCM/ALPR420/020     '},
    {"house_id": 'TX63166             '}
]

for x in sorted(data, key=lambda k: k['house_id']):
        print x


However, my data is structured like below. The data does not sort for me. If someone could help me with a solution I would appreciate it.
Thanks.

detail_data = ['MCM/ALPR420/020     ',
               'ROT/METR020/020     ',
               'MCM/ALPR420/020     ',
               'TX63166             ']

for item in detail_data:

    data = [
        {"house_id": item}
    ]

    for x in sorted(data, key=lambda k: k['house_id']):
        print x


my expected output:

{"house_id": 'MCM/ALPR420/020     '}
{"house_id": 'MCM/ALPR420/020     '}
{"house_id": 'ROT/METR020/020     '}
{"house_id": 'TX63166             '}


Is This A Good Question/Topic? 0
  • +

Replies To: Ordering a list of dictionaries by key

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2153
  • View blog
  • Posts: 3,315
  • Joined: 21-June 11

Re: Ordering a list of dictionaries by key

Posted 05 April 2013 - 06:57 AM

In your second piece of code, data only ever contains a single element. Sorting a list with a single element will obviously not have any effect.
Was This Post Helpful? 0
  • +
  • -

#3 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8009
  • View blog
  • Posts: 13,716
  • Joined: 19-March 11

Re: Ordering a list of dictionaries by key

Posted 05 April 2013 - 07:13 AM

If you want detail_data sorted, couldn't you just sort it?

You can dictify it later if you like....
Was This Post Helpful? 0
  • +
  • -

#4 donfanzu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 08-April 12

Re: Ordering a list of dictionaries by key

Posted 06 April 2013 - 03:16 PM

Hi guys, thanks for your replies. Yes I could indeed sort my 'detail_data' and then put it into a dictionary, in the earlier example I gave.
But I can't do it in my actual code. I'm new to python and don't think i fully understand the data structures I am creating/using.

What im trying to do is import a file, where I create fields by the characters in each line and then put my data it into a list of dictionaries before doing some formatting and inserting dictionaries into a mongo database.
I have my data in the correct format, but can't seem to sort it by "house_id".

here is my code:

the_file = open('myfile.txt', 'r')
data_list = the_file.readlines()


def bulk_data(line):
    return {'event_type': line[0:2],
            'event_sequence': line[3:7],
            'house_number': line[79:99]}


detail_data = [bulk_data(line) for line in data_list]

for item in detail_data:
    new_data = {
        'event_type': item['event_type'],
        'house_number': item['house_number'],
        'event_sequence': item['event_sequence'],
        'date_created': datetime.datetime.utcnow(),
        'more_formatting': 'event stuff'
    }

    print new_data
    
    #Sorting my data by house_number (the stuff I'm doing wrong)
    # for x in sorted(new_data, key=lambda k: k['house_number']):
    #     print x




The output of my new_data is:
{'house_number': 'IF00001             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992108), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0001'}
{'house_number': 'THA/HXGT652/030     ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992343), 'more_formatting': 'event stuff', 'event_type': 'P ', 'event_sequence': '0002'}
{'house_number': 'IF00001             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992479), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0003'}
{'house_number': 'EUD/PTNN17/1800     ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992625), 'more_formatting': 'event stuff', 'event_type': 'P ', 'event_sequence': '0004'}
{'house_number': 'PR10029             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992748), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0005'}
{'house_number': 'PM230938            ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 993021), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0006'}
{'house_number': 'PM230734            ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 993184), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0007'}
{'house_number': 'IF00001             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 993469), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0008'}



What I ideally would like is to sort my data by 'house_id and sequence number in ascending order. The commented out code was my earlier attempt at sorting, which obviously failed.
If someone could point me in the right direction it would be great, thanks.
Was This Post Helpful? 0
  • +
  • -

#5 janotte  Icon User is offline

  • code > sword
  • member icon

Reputation: 990
  • View blog
  • Posts: 5,141
  • Joined: 28-September 06

Re: Ordering a list of dictionaries by key

Posted 16 April 2013 - 04:57 AM

How about loop through the data list and get the house numbers into a list.
Then sort the list of house numbers.
Then loop through the sorted house number list and extract the dict data where the house number matches the house number in the sorted list.

Not elegant but it should work.

If you get that working then adding more refined sorting should be achievable.
Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,855
  • Joined: 16-October 07

Re: Ordering a list of dictionaries by key

Posted 16 April 2013 - 06:11 AM

The sort you tried looks fine. Maybe I'm missing something.

>>> new_data = [
...     {'house_number': 'IF00001             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992108), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0001'},
...     {'house_number': 'THA/HXGT652/030     ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992343), 'more_formatting': 'event stuff', 'event_type': 'P ', 'event_sequence': '0002'},
...     {'house_number': 'IF00001             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992479), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0003'},
...     {'house_number': 'EUD/PTNN17/1800     ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992625), 'more_formatting': 'event stuff', 'event_type': 'P ', 'event_sequence': '0004'},
...     {'house_number': 'PR10029             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 992748), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0005'},
...     {'house_number': 'PM230938            ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 993021), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0006'},
...     {'house_number': 'PM230734            ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 993184), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0007'},
...     {'house_number': 'IF00001             ', 'date_created': datetime.datetime(2013, 4, 6, 22, 3, 46, 993469), 'more_formatting': 'event stuff', 'event_type': 'I ', 'event_sequence': '0008'},
...     ]
>>> 
>>> sorted_data = sorted(new_data, key=lambda k: k['house_number'])
>>> print '\n'.join(i['house_number'] + ' ' + i['event_sequence'] for i in sorted_data)
EUD/PTNN17/1800      0004
IF00001              0001
IF00001              0003
IF00001              0008
PM230734             0007
PM230938             0006
PR10029              0005
THA/HXGT652/030      0002
>>> 



If you want something more complex than the one key... you have to roll your own compare.

e.g.
>>> def myCmp(x,y):
...     if x['house_number'] < y['house_number']:
...             return -1
...     elif x['house_number'] > y['house_number']:
...             return 1
...     elif x['event_sequence'] < y['event_sequence']:
...             return 1
...     elif x['event_sequence'] > y['event_sequence']:
...             return -1
...     else:
...             return 0
... 
>>> 
>>> print '\n'.join(i['house_number'] + ' ' + i['event_sequence'] for i in sorted(new_data, cmp=myCmp))
EUD/PTNN17/1800      0004
IF00001              0008
IF00001              0003
IF00001              0001
PM230734             0007
PM230938             0006
PR10029              0005
THA/HXGT652/030      0002
>>> 



Here, I chose house_number ascending, event_sequence descending.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1