1

I have a function that returns an energy associated with a vector in 3D space, F(i,j,k).

F() is a slow function, so I have a dictionary that checks if F() has been called for a specific i,j,k, and if it has then I just take that value from the dictionary.

I'm currently doing this as:

key = "_".join( [ str(i), str(j), str(k)  ])

if key not in dic: 
    dic[key] = F(i,j,k)

Energy = dic[key]

Is there a better way to create a key than by joining the vectors like this?

1
  • For future reference, that first line can be simplified using map, to key = "_".join(map(str, (i, j, k))) Commented Jun 23, 2014 at 9:44

2 Answers 2

8

Dictionary keys can be anything hashable; a tuple of the 3 values does fine:

key = i, j, k  # a comma makes this a tuple
try:
    Energy = dic[key]
except KeyError:
    Energy = dic[key] = F(i, j, k)

I'm using exception handling here (asking for forgiveness) rather than explicitly testing if the key is present (asking for permission); the former is faster when the absence of the key is the key is the norm.

Sign up to request clarification or add additional context in comments.

6 Comments

I was using shelve to store my dictionaries. Apparently this won't work with tuples as keys. Is pickle the next best alternative?
@egoburnswell: shelve uses pickle as the implementation. Tuple keys should work just fine with shelve; what is the error you see?
'TypeError: String or Integer object expected for key, tuple found'
@egoburnswell: My apologies, I indeed see that shelve is documented as only accepting strings as keys. That's because the values are pickled, but these are then stored in a DBM-style file, and it is that format that limits your keys.
@egoburnswell: Either store your dictionary nested in shelve (shelveobj['data'] = yourdict, make sure to reassign to that key on changes) or use only Pickle, in that case.
|
1

Since Python dicts can take any hashable object as keys[1], you can just use the (i, j, k) tuple:

if (i, j, k) not in dic:
    dic[(i, j, k)] = F(i,j,k)
Energy = dic[(i, j, k)]

[1] https://docs.python.org/2/library/stdtypes.html#mapping-types-dict

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.