Pythonic alternative to nested dictionaries and lists

Viewed 972

I am currently using a dictionary keyed on seconds since epoch combined with a nested dictionary and list to store and look up events. The strength is that I can quickly look up a value with good performance (think hash). The weakness is that it is clumsy to search and manipulate the subsequent contents. I can't help but think my approach is not very Pythonic so I am looking for suggestions.

Here is a simple example using integers rather than seconds since epoch:

D = {}

D[1] = {"995" : ["20905", "200101"]}
D[2] = {"991" : ["20901"], "995" : ["20905"]}

eventCode = '995'
error = '90900'

# find entry
if 1 in D:
    # if eventCode exists then append error code
    if D[1][eventCode]:
        D[1][eventCode].append(error)

I can look up D[1] quickly, however the remainder of the code doesn't seem very pythonic. Any suggestions or am I paranoid?

I should check to see if "error" is already in the list. However, I am unsure how to check for membership in this construct. This snippet does not work for me:

if error not in D[1][eventCode]
2 Answers
Related