Data Structure Question

Alex Martelli aleaxit at yahoo.com
Sun Jun 17 16:12:48 EDT 2001


"Mike Johnson" <ffp_randjohnson at yahoo.com> wrote in message
news:20010617.090337.1987231011.7258 at behemoth.miketec.com...
    ...
> I've been looking for the Python equivalent of a Perl hashed array. I
> learned about dictionaries from the help, but they don't work in quite the
> same way since my keys are not always unique.

I may be confused, but surely Perl's hashes DO work identically -- if
"a key is not unique", reassigning to the hash's entry for that key will
rebind and forget the previous assignment.


> I was hoping to do something like:
>
> diction['thekey']=value
>
> in a loop. The key and the value are not always unique, so 'diction' ends
> up dropping some information.

But a Perl hash would behave identically!  What am I missing?


> On thing that did work was to embed a nested dictionary into a list.
>
> list=[]
> diction={}
>
> diction['key']='somedata'
> list.append(diction)
> diction={}
> (repeat)
>
> But... This makes it a terrible pain to search and count keys....

This looks like a complicated way to prepare a list of pairs (two-element
tuples) -- if that's what you want, it's simpler to do:
    list.append(('key', 'somedata'))
    (repeat)
although searching and counting keys, while anything but 'a terrible
pain', will be slow:

def searchakey(thelist, akey):
    return [(key,value) for key,value in thelist if key==akey]

def countakey(thelist, akey):
    result = 0
    for key, value in thelist:
        if key==akey:
            result += 1
    return result
    # or the slower but niftier: return len(searchakey(thelist, akey))


Anyway, a dictionary of lists seems more suited for your needs than
a list of pairs:
    dict = {}

    dict.setdefault('key',[]).append('somedata')
    (repeat)

and now:

def searchakey(dict, akey):
    return dict[akey]

def countakey(dict, akey):
    return len(searchakey(dict,akey))  # now also quite cheap:-)


Alex







More information about the Python-list mailing list