Newbie question: eliminating entries in dict

Peter Otten __peter__ at web.de
Wed Nov 26 04:17:08 EST 2003


sean wrote:

> I had tried something very similar to that but ended up with the same
> error I am getting now.
> 
> Traceback (most recent call last):
>   File "C:\Python23\trial.py", line 93, in -toplevel-
>     d = ([(k,v) for k, v in a.iteritems() if (k.split("*", 1)[1]) not in
>     b])
> IndexError: list index out of range
> 
> Changing the [1] to a [0] makes the Error go away, but compares the wrong
> part of the entry.
> 
> Any ideas?

Assuming you are using the same variable names as in your original post,
it's not similar enough :-( You swapped a and b. Actually, a string is only
split in n+1 parts if it contains at least n separators:

>>> "a-b".split("-", 1)
['a', 'b']
>>> "a-b".split("-", 2)
['a', 'b']
>>> "a-b".split("-", 3)
['a', 'b']
>>> "a".split("-", 1)
['a']
>>> "a-b-c-d".split("-", 1)
['a', 'b-c-d']
>>>

Get the idea?

A more robust approach would be:

def keepItem(email, black):
    try:
        dom = email.split("@")[1]
    except IndexError:
        return False # discard malformed entries
    return dom not in black

good = [(addr, freq) for addr, freq in emails.iteritems() if keepItem(addr,
black)]

Note the use of suggestive variable names to make the code easier to read
and debug.
By the way, when you are still developing your understanding of Python, an
error is easier to find in a small commandline example than in a line
somewhere in a larger script.

Peter




More information about the Python-list mailing list