473,387 Members | 1,574 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,387 software developers and data experts.

Ordered dictionary?

I need to associate a string (key) with an integer (value). A dictionary
would do the job, except for the fact that it must be ordered. I also
need to look up the value for a specific key easily, so a list of tuples
wouldn't work.

Jul 18 '05 #1
14 3150
Leif K-Brooks wrote:
I need to associate a string (key) with an integer (value). A dictionary
would do the job, except for the fact that it must be ordered. I also
need to look up the value for a specific key easily, so a list of tuples
wouldn't work.


A dictionary could be used. When you need to managed the items in order,
what you would do is called dict.keys(), followed by a sort.

I don't know if this helps at all...

--
Glitch

http://andres980.tripod.com/

"That is the law of the jungle. The hunters and the hunted. Scrap or
be scrapped!"
"Animals hunt to SURVIVE!"
"And what do you think war is about?!"
-- Dinobot and Tigatron, "The Law of the Jungle"
Jul 18 '05 #2
Leif K-Brooks wrote:
I need to associate a string (key) with an integer (value). A dictionary
would do the job, except for the fact that it must be ordered. I also
need to look up the value for a specific key easily, so a list of tuples
wouldn't work.


How must the dictionary be ordered? Do you need the keys or the values
sorted?

- Josiah
Jul 18 '05 #3
>>>>> "Leif" == Leif K-Brooks <eu*****@ecritters.biz> writes:

Leif> I need to associate a string (key) with an integer
Leif> (value). A dictionary would do the job, except for the fact
Leif> that it must be ordered. I also need to look up the value
Leif> for a specific key easily, so a list of tuples wouldn't
Leif> work.

google : python ordered dictionary
click : I'm feeling lucky

JDH

Jul 18 '05 #4
# I need to associate a string (key) with an integer (value). A dictionary
# would do the job, except for the fact that it must be ordered. I also
# need to look up the value for a specific key easily, so a list of tuples
# wouldn't work.

As the other posts on this thread suggest, dictionaries -- by virtue
of their structure -- have no inherently meaningful ordering. You'll
have to either sort the keys (the easy way) or design a wrapper for
the dictionary that maintains a sorted list of the dictionary's
keys and updates it as necessary (the hard way).

--

Jonathan Daugherty
http://www.cprogrammer.org

"It's a book about a Spanish guy called Manual, you should read it."
-- Dilbert

Jul 18 '05 #5
"Leif K-Brooks" <eu*****@ecritters.biz> wrote in message
news:le******************@newshog.newsread.com...
I need to associate a string (key) with an integer (value). A dictionary
would do the job, except for the fact that it must be ordered. I also
need to look up the value for a specific key easily, so a list of tuples
wouldn't work.

If you really need to access the dictionary in sorted key order, is this so
difficult?

dKeys = d.keys()
dKeys.sort()
for k in dKeys:
# do stuff with k and d[k], such as:
print k, "=", d[k]

Or if you are worried about updates to d between the time of key retrieval
and time of traversal (for instance, if a separate thread were to delete one
of the keyed entries), take a snapshot as a list:

dItems = d.items() # from here on, you are insulated from changes to
dictionary 'd'
dItems.sort() # implicitly sorts by key
dItems.sort( lambda a,b: a[1]-b[1] ) # sorts by value, if you so prefer
for k,v in dItems:
# do stuff with k and v, such as:
print k, "=", v # <-- added benefit here of not re-accessing
the list by key

-- Paul
Jul 18 '05 #6
Josiah Carlson wrote:
I need to associate a string (key) with an integer (value). A
dictionary would do the job, except for the fact that it must be
ordered. I also need to look up the value for a specific key easily,
so a list of tuples wouldn't work.

How must the dictionary be ordered? Do you need the keys or the values
sorted?


Sorry for not making that clear, I need it sorted by the order of
insertion. Looks like
http://aspn.activestate.com/ASPN/Coo.../Recipe/107747 might do
what I want...

Jul 18 '05 #7
Leif K-Brooks wrote:
Josiah Carlson wrote:
I need to associate a string (key) with an integer (value). A
dictionary would do the job, except for the fact that it must be
ordered. I also need to look up the value for a specific key easily,
so a list of tuples wouldn't work.


How must the dictionary be ordered? Do you need the keys or the
values sorted?

Sorry for not making that clear, I need it sorted by the order of
insertion. Looks like
http://aspn.activestate.com/ASPN/Coo.../Recipe/107747 might do
what I want...


That should do. Looks promising, but I think it uses the old style of
extending the dictionary (Not that it's bad) ...

--
Glitch

http://andres980.tripod.com/

One good shot is worth a hundred bad ones!
-- Big Shot (G1)
Jul 18 '05 #8
Op 2004-01-22, Paul McGuire schreef <pt***@users.sourceforge.net>:
"Leif K-Brooks" <eu*****@ecritters.biz> wrote in message
news:le******************@newshog.newsread.com...
I need to associate a string (key) with an integer (value). A dictionary
would do the job, except for the fact that it must be ordered. I also
need to look up the value for a specific key easily, so a list of tuples
wouldn't work.

If you really need to access the dictionary in sorted key order, is this so
difficult?

dKeys = d.keys()
dKeys.sort()
for k in dKeys:
# do stuff with k and d[k], such as:
print k, "=", d[k]

Or if you are worried about updates to d between the time of key retrieval
and time of traversal (for instance, if a separate thread were to delete one
of the keyed entries), take a snapshot as a list:

dItems = d.items() # from here on, you are insulated from changes to
dictionary 'd'
dItems.sort() # implicitly sorts by key
dItems.sort( lambda a,b: a[1]-b[1] ) # sorts by value, if you so prefer
for k,v in dItems:
# do stuff with k and v, such as:
print k, "=", v # <-- added benefit here of not re-accessing
the list by key


Well I too sometimes need the keys in a dictionary to be sorted and your
solutions wouldn't help. The problem is the following.

I have a number of key value pairs, like names and telephone numbers.
Just more subject to change. Now I want the telephone numbers of everyone
whose name starts with "jan".

Or I just inserted a name and want to know who is alphabetically next.
Or I want to know who is first or last.

--
Antoon Pardon
Jul 18 '05 #9
Hi

Maybe this code will help:

import operator

def filterList(p_list, p_value):
l_len = len(p_list)
l_temp = map(None, (p_value,)*l_len, p_list)
l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp)
return map(operator.getitem, l_temp, (-1,)*len(l_temp))

phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'}
names_list = filterList(phones_dict.keys(), 'jan')
phones_list = map(phones_dict.get, names_list)

print phones_list

This extracts from the dictionary the telephone(values) numbers for
names(keys) starting with 'jan'...

Dragos
Op 2004-01-22, Paul McGuire schreef <pt***@users.sourceforge.net>:
"Leif K-Brooks" <eu*****@ecritters.biz> wrote in message
news:le******************@newshog.newsread.com...
I need to associate a string (key) with an integer (value). A dictionary would do the job, except for the fact that it must be ordered. I also
need to look up the value for a specific key easily, so a list of tuples wouldn't work.

If you really need to access the dictionary in sorted key order, is this so difficult?

dKeys = d.keys()
dKeys.sort()
for k in dKeys:
# do stuff with k and d[k], such as:
print k, "=", d[k]

Or if you are worried about updates to d between the time of key retrieval and time of traversal (for instance, if a separate thread were to delete one of the keyed entries), take a snapshot as a list:

dItems = d.items() # from here on, you are insulated from changes to dictionary 'd'
dItems.sort() # implicitly sorts by key
dItems.sort( lambda a,b: a[1]-b[1] ) # sorts by value, if you so prefer for k,v in dItems:
# do stuff with k and v, such as:
print k, "=", v # <-- added benefit here of not re-accessing the list by key


Well I too sometimes need the keys in a dictionary to be sorted and your
solutions wouldn't help. The problem is the following.

I have a number of key value pairs, like names and telephone numbers.
Just more subject to change. Now I want the telephone numbers of everyone
whose name starts with "jan".

Or I just inserted a name and want to know who is alphabetically next.
Or I want to know who is first or last.

--
Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #10
Hi Dragos,
def filterList(p_list, p_value):
l_len = len(p_list)
l_temp = map(None, (p_value,)*l_len, p_list)
l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp)
return map(operator.getitem, l_temp, (-1,)*len(l_temp)) phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'}
names_list = filterList(phones_dict.keys(), 'jan')
phones_list = map(phones_dict.get, names_list) This extracts from the dictionary the telephone(values) numbers for
names(keys) starting with 'jan'...


Why you didn't used the string.startswith(...) method?

I wrote this:

d={'carmine':'123456','carmela':'4948399','pippo': '39938303'}
for name,number in d.items():
if name.startswith('car'):
print name,number

This also extract from the dictionay all the (name,number) pairs whose
name starts with a given substring ('car' in the example).

Thanks for your answer
Jul 18 '05 #11
Carmine Moleti wrote:
Hi Dragos,

def filterList(p_list, p_value):
l_len = len(p_list)
l_temp = map(None, (p_value,)*l_len, p_list)
l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp)
return map(operator.getitem, l_temp, (-1,)*len(l_temp))


phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'}
names_list = filterList(phones_dict.keys(), 'jan')
phones_list = map(phones_dict.get, names_list)


This extracts from the dictionary the telephone(values) numbers for
names(keys) starting with 'jan'...

Why you didn't used the string.startswith(...) method?

I wrote this:

d={'carmine':'123456','carmela':'4948399','pippo': '39938303'}
for name,number in d.items():
if name.startswith('car'):
print name,number

This also extract from the dictionay all the (name,number) pairs whose
name starts with a given substring ('car' in the example).

Thanks for your answer


Something strange is that for short 'other' strings
string[:len(other)] == other
#is faster than
string.startswith(other)

Maybe find is faster than startswith.

- Josiah
Jul 18 '05 #12
"Paul McGuire" <pt***@users.sourceforge.net> wrote...
If you really need to access the dictionary in sorted key order, is this so
difficult?


That was not the original poster's question. Order is semantic
information which a dictionary does not record or represent in any
way.
David.
Jul 18 '05 #13
> Well I too sometimes need the keys in a dictionary to be sorted and your
solutions wouldn't help. The problem is the following.

I have a number of key value pairs, like names and telephone numbers.
Just more subject to change. Now I want the telephone numbers of everyone whose name starts with "jan".

Or I just inserted a name and want to know who is alphabetically next.
Or I want to know who is first or last.


A python dict is not very well suited to this, especially for large numbers
of key,value pairs. However, if you do pull out sorted lists of keys, use
the bisect module to find specific keys. log(n) behavior is fine.

A table with a btree index is designed for the things your want to do.
There is a btree,py in zope (by Tim Peters, I believe), but I do not know
how 'extractable' it is. You could search the archives.

Terry J. Reedy


Jul 18 '05 #14
In article <99**************************@posting.google.com >,
dw***********@botanicus.net (David M. Wilson) wrote:
"Paul McGuire" <pt***@users.sourceforge.net> wrote...
If you really need to access the dictionary in sorted key order, is this so
difficult?


That was not the original poster's question. Order is semantic
information which a dictionary does not record or represent in any
way.


Wants order of insertion. Best I can think of is

class OrderedDict (dict):
"Retains order-of-insertion in the dictionary"
def __setitem__ (self, key, value):
dict.__setitem__ (self, key, (len (self), value,) )

def __getitem__ (self, key):
return dict.__getitem__ (self, key)[1]

def ordered_items (self):
i = [(v, k) for (k, v) in self.items()]
i.sort()
return [(k, v[1]) for (v, k) in i]

# end class OrderedDict

if __name__ == '__main__':
D = OrderedDict()
D['oranges'] = 41
D['lemons'] = 22
D['limes'] = 63

print D
print D.ordered_items()

Possibly other refinenemts: __init__ that inserts from a
sequence of 2-tuples, keeping a sequence number as a class
attribute instead of using len, etc.

Regards. Mel.
Jul 18 '05 #15

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

Similar topics

210
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again...
8
by: Fuzzyman | last post by:
Sorry for this hurried message - I've done a new implementation of out ordered dict. This comes out of the discussion on this newsgroup (see blog entry for link to archive of discussion). See...
22
by: bearophileHUGS | last post by:
>From this interesting blog entry by Lawrence Oluyede: http://www.oluyede.org/blog/2006/07/05/europython-day-2/ and the Py3.0 PEPs, I think the people working on Py3.0 are doing a good job, I am...
1
by: Fuzzyman | last post by:
After a break of almost a year there has been an update to `odict the Ordered Dictionary <http://www.voidspace.org.uk/python/odict.html>`_. The latest version is 0.2.2, with changes implemented...
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: 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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.