Newbie question: eliminating entries in dict
__peter__ at web.de
Wed Nov 26 10:17:08 CET 2003
> 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)) not in
> IndexError: list index out of range
> Changing the  to a  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".split("-", 2)
>>> "a-b".split("-", 3)
>>> "a".split("-", 1)
>>> "a-b-c-d".split("-", 1)
Get the idea?
A more robust approach would be:
def keepItem(email, black):
dom = email.split("@")
return False # discard malformed entries
return dom not in black
good = [(addr, freq) for addr, freq in emails.iteritems() if keepItem(addr,
Note the use of suggestive variable names to make the code easier to read
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.
More information about the Python-list