Home

Search

Python Dictionary Methods

Add keys and values, and then look them up, with a dictionary. Test lookup performance.

Dictionary. Consider a language. Each word maps to a meaning. A book is a written work. A cloud is floating water. In a dictionary we map keys (words) to values (meanings).

Dictionary methods. Python dictionaries are maps. With square brackets, we assign and access a value at a key. With get() we can specify a default result.{} (Initialize Dictionary)copydel (Remove Key)dict()dict(a)dict.fromkeysfor (Loop Over Dictionary)get(a)get(a, b)in (Search Dictionary)itemskeyslen (Element Count)sortupdatevalues

Memoize. One classic optimization is called memoization. And this can be implemented easily with a dictionary. In memoization, a function (def) computes its result.MemoizeMemoize: Lower Dictionary
And: Once the computation is done, it stores its result in a cache. In the cache, the argument is the key. And the result is the value.

Memoization, continued. When a memoized function is called, it first checks this cache to see if it has been (with this argument) run before.
And: If it has, it returns its cached (memoized) return value. No further computations need be done.
Note: If a function is only called once with the argument, memoization has no benefit. And with many arguments, it usually works poorly.

Add order performance. When hashes collide, a linear search must be done to locate a key in the dictionary. If we add a key earlier, it is faster to locate.Dictionary Order

String key performance. In another test, I compared string keys. I found that long string keys take longer to look up than short ones. Shorter keys are faster.Dictionary String Key

KeyError. If we try to access a key that is not present with direct syntax, we will get a KeyError. This can be avoided with the get() method.KeyError

Counter. For frequencies, we can use a special Counter from the collections module. This can make counters easier to add in programs.Counter

A summary. A dictionary is usually implemented as a hash table. Here a special hashing algorithm translates a key (often a string) into an integer.

For a speedup, this integer is used to locate the data. This reduces search time. For programs with performance trouble, using a dictionary is often the initial path to optimization.

Home
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.