Ordered dictionary?
Dragos Chirila
d.chirila at bucarest.finsiel.ro
Fri Jan 23 04:43:11 EST 2004
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 <ptmcg at users.sourceforge.net>:
> > "Leif K-Brooks" <eurleif at ecritters.biz> wrote in message
> > news:leWPb.231$af7.162835 at 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
>
More information about the Python-list
mailing list