473,383 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Sorting dictionary by 'sub' value

I have a dictionary of images. I wish to sort the dictionary 'v' by a
dictionary value using python 2.3. The dictionary value is the date
attribute as shown here:

v[imagename][9]['date']

This attribute is an extracted EXIF value from the following set:

data element [9] of v[imagename]:

{'now' : datetime.date(2005, 3, 7),
'y' : (0x011B) Ratio=72 @ 182,
'ctime' : datetime.date(2005, 3, 7),
'width' : (0xA002) Long=1024 @ 434,
'length' : (0xA003) Long=768 @ 446,
'date' : (0x9004) ASCII=2004:12:07 00:18:20 @ 514,
'x' : (0x011A) Ratio=72 @ 174,
'model' : (0x0110) ASCII=PENTAX Optio 330 @ 156,
'size' : 367415L,
'orientation' : (0x0112) Short=1 @ 42}

Thanks,
Rory

--
Rory Campbell-Lange
<ro**@campbell-lange.net>
<www.campbell-lange.net>
Jul 18 '05 #1
4 2880
> I have a dictionary of images. I wish to sort the dictionary 'v' by a
dictionary value using python 2.3. The dictionary value is the date
attribute as shown here:

v[imagename][9]['date']

This attribute is an extracted EXIF value from the following set:

data element [9] of v[imagename]:

{'now' : datetime.date(2005, 3, 7),
'y' : (0x011B) Ratio=72 @ 182,
'ctime' : datetime.date(2005, 3, 7),
'width' : (0xA002) Long=1024 @ 434,
'length' : (0xA003) Long=768 @ 446,
'date' : (0x9004) ASCII=2004:12:07 00:18:20 @ 514,
'x' : (0x011A) Ratio=72 @ 174,
'model' : (0x0110) ASCII=PENTAX Optio 330 @ 156,
'size' : 367415L,
'orientation' : (0x0112) Short=1 @ 42}

You can't sort dicts - they don't impose an order on either key or value.
There are ordered dict implementations out there, but AFAIK the only keep
the keys sorted, or maybe the (key,values) in the insertion order.

But maybe this helps you:

l = v.items()
l.sort(lambda a, b: cmp(a[9]['date'], b[9]['date'])
--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
Diez B. Roggisch wrote:
I have a dictionary of images. I wish to sort the dictionary 'v' by a
dictionary value using python 2.3. The dictionary value is the date
attribute as shown here:

v[imagename][9]['date']
...


You can't sort dicts - they don't impose an order on either key or value.
There are ordered dict implementations out there, but AFAIK the only keep
the keys sorted, or maybe the (key,values) in the insertion order.

But maybe this helps you:

l = v.items()
l.sort(lambda a, b: cmp(a[9]['date'], b[9]['date'])


In 2.4, this is simple:

ordered_keys = sorted(v, key=lambda name: v[name][9]['date'])

In 2.3, or earlier, use "decorate-sort-undecorate":

decorated = [(value[9]['date'], key)
for key, value in v.iteritems()]
decorated.sort()
result = [key for key, date in decorated]

--Scott David Daniels
Sc***********@Acm.Org

Jul 18 '05 #3
Thank you all very much for your help.

I did the following and it works:

imgs=v.keys()
imgs.sort(lambda a,b: cmp(
time.strptime(str(v[a][9]['date']), '%Y:%m:%d %H:%M:%S'),
time.strptime(str(v[b][9]['date']), '%Y:%m:%d %H:%M:%S'))
)
for i in imgs:
...

Regards,
Rory

On 08/03/05, Diez B. Roggisch (de*********@web.de) wrote:
l = v.items()
l.sort(lambda a, b: cmp(a[9]['date'], b[9]['date'])


On 08/03/05, Scott David Daniels (Sc***********@Acm.Org) wrote:
You can't sort dicts - they don't impose an order on either key or value.
There are ordered dict implementations out there, but AFAIK the only keep
the keys sorted, or maybe the (key,values) in the insertion order.

But maybe this helps you:

l = v.items()
l.sort(lambda a, b: cmp(a[9]['date'], b[9]['date'])


In 2.4, this is simple:

ordered_keys = sorted(v, key=lambda name: v[name][9]['date'])

In 2.3, or earlier, use "decorate-sort-undecorate":

decorated = [(value[9]['date'], key)
for key, value in v.iteritems()]
decorated.sort()
result = [key for key, date in decorated]


On 08/03/05, Batista, Facundo (FB******@uniFON.com.ar) wrote:
temp_list = [ (x[1][1], x[0]) for x in d.items() ] .... temp_list.sort()
for (tmp, key) in temp_list:

--
Rory Campbell-Lange
<ro**@campbell-lange.net>
<www.campbell-lange.net>
Jul 18 '05 #4
Rory Campbell-Lange wrote:
Thank you all very much for your help.

I did the following and it works:

imgs=v.keys()
imgs.sort(lambda a,b: cmp(
time.strptime(str(v[a][9]['date']), '%Y:%m:%d %H:%M:%S'),
time.strptime(str(v[b][9]['date']), '%Y:%m:%d %H:%M:%S'))
)
for i in imgs:
...


Cool. If you ever find that this is a speed problem, it's worth
pointing out that the decorate-sort-undecorate pattern is usually
slightly faster:

------------------------------ test.py ------------------------------
import datetime
import time

# returns data in a similar format to yours
def get_data(n):
today = datetime.datetime(2005, 3, 8)
deltas = [datetime.timedelta(seconds=1e6*i)
for i in xrange(-n, n)]
times = [(today + delta).strftime('%Y:%m:%d %H:%M:%S')
for delta in deltas]
return dict([(i, {9:{'date':time}})
for i, time in enumerate(times)])

def sortcmp(data):
imgs = data.keys()
imgs.sort(lambda a,b: cmp(
time.strptime(str(data[a][9]['date']),
'%Y:%m:%d %H:%M:%S'),
time.strptime(str(data[b][9]['date']),
'%Y:%m:%d %H:%M:%S'))
)
return imgs

def sortdsu(data):
decorated = [(time.strptime(str(data[key][9]['date']),
'%Y:%m:%d %H:%M:%S'), key)
for key in data]
decorated.sort()
return [key for date, key in decorated]

# Requires 2.4
def sortkey(data):
def value(key):
return time.strptime(str(data[key][9]['date']),
'%Y:%m:%d %H:%M:%S')
return sorted(data, key=value)
---------------------------------------------------------------------

And the timing results:

[D:\Steve]$ python -m timeit -s "import test; d = test.get_data(1000)"
"test.sortcmp(d)"
10 loops, best of 3: 274 msec per loop

[D:\Steve]$ python -m timeit -s "import test; d = test.get_data(1000)"
"test.sortdsu(d)"
10 loops, best of 3: 131 msec per loop

# Requires 2.4

[D:\Steve]$ python -m timeit -s "import test; d = test.get_data(1000)"
"test.sortkey(d)"
10 loops, best of 3: 131 msec per loop

HTH,

STeVe
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: shalendra chhabra | last post by:
Hi, I just had a tryst with python. I was wondering if python is good enough to do this kind of job -- for it has extensive support of string and pattern matching, ordering and list handling. ...
4
by: dont bother | last post by:
This is really driving me crazy. I have a dictionary feature_vectors{}. I try to sort its keys using #apply sorting on feature_vectors sorted_feature_vector=feature_vectors.keys()...
7
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) ...
19
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to...
1
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex...
1
by: Martin Widmer | last post by:
Hi Folks. When I iterate through my custom designed collection, I always get the error: "Unable to cast object of type 'System.Collections.DictionaryEntry' to type...
1
by: sdunkerson | last post by:
I think this will be a good one for anyone who fancies themselves a wiz with manipulating data structure in vb.net. Imagine a Dictionary collection of Object "A". One of the properties of Object...
4
by: =?Utf-8?B?TUdSaWRlb3V0?= | last post by:
Hello, I have a SQL string that pulls data out of a database - I then calculate completerates based on Hours and # of Completes. I want to sort this data (FieldID and CompleteRates) by CompleteRate...
1
by: Ahmed Yasser | last post by:
Hi all, i have a problem with the datagridview sorting, the problem is a bit complicated so i hope i can describe in the following steps: 1. i have a datagridview with two columns...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.