473,809 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
14 3191
Hi Dragos,
def filterList(p_li st, p_value):
l_len = len(p_list)
l_temp = map(None, (p_value,)*l_le n, p_list)
l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp)
return map(operator.ge titem, l_temp, (-1,)*len(l_temp) ) phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'}
names_list = filterList(phon es_dict.keys(), 'jan')
phones_list = map(phones_dict .get, names_list) This extracts from the dictionary the telephone(value s) numbers for
names(keys) starting with 'jan'...


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

I wrote this:

d={'carmine':'1 23456','carmela ':'4948399','pi ppo':'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_li st, p_value):
l_len = len(p_list)
l_temp = map(None, (p_value,)*l_le n, p_list)
l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp)
return map(operator.ge titem, l_temp, (-1,)*len(l_temp) )


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


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

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

I wrote this:

d={'carmine':'1 23456','carmela ':'4948399','pi ppo':'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.startswi th(other)

Maybe find is faster than startswith.

- Josiah
Jul 18 '05 #12
"Paul McGuire" <pt***@users.so urceforge.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***********@b otanicus.net (David M. Wilson) wrote:
"Paul McGuire" <pt***@users.so urceforge.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
10578
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 I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
8
1676
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 the latest blog entry to get at it : http://www.voidspace.org.uk/python/weblog/index.shtml Criticism solicited (honestly) :-) We (Nicola Larosa and I) haven't yet made any optimisations - but there
22
2380
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 not expert enough (so I don't post this on the Py3.0 mailing list), but I agree with most of the things they are agreeing to. Few notes: - input() vanishes and raw_input() becomes sys.stdin.readline(). I think a child that is learning to program...
1
1498
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 by Nicola Larosa. Despite over 700 downloads since May (plus 1300 as part of `pythonutils <http://www.voidspace.org.uk/python/pythonutils.html>`_) there have been no bug reports, only improvements _. {sm;:-)} * `Quick Download
0
9603
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10387
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7662
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.