Python dictionary

A Python Dictionary

By Monty, 26th May 2015

Python dictionary

Python dictionary

This is simply a dictionary of Python keywords, implemented as – of course – a Python dictionary! Dictionaries are key:value pairs. The value can be any object, such as a tuple of strings. The first item in the tuple is part of the URL to documentation at Python.org, and the second item is a brief description of the keyword’s purpose. In a perpetual loop, we: prompt the user for the word to lookup; quit if required; try to lookup the word. If successful we print the results, otherwise give the user a list of the keywords in the dictionary.
Note that we’re using Python 2 print instead of Python print() due to trinket limitations.

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

Wikipedia:

In computer science, an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.

Operations associated with this data type allow:

  • the addition of a pair to the collection
  • the removal of a pair from the collection
  • the modification of an existing pair
  • the lookup of a value associated with a particular key

The dictionary problem is a classic computer science problem: the task of designing a data structure that maintains a set of data during 'search', 'delete', and 'insert' operations. The two major solutions to the dictionary problem are a hash table or a search tree. In some cases it is also possible to solve the problem using directly addressed arrays, binary search trees, or other more specialized structures.

Many programming languages include associative arrays as primitive data types, and they are available in software libraries for many others. Content-addressable memory is a form of direct hardware-level support for associative arrays.

Associative arrays have many applications including such fundamental programming patterns as memoization and the decorator pattern.

%d bloggers like this: