Python:Hash Maps

From Progzoo
Jump to: navigation, search

A hash table (also known as associative array, lookup table, dictionary, hash) is a way of storing values against keys. Often the keys are strings, in this example the values are numbers.
You can create an associated array using curly braces:

  • a = {}

And then add some elements to it:

  • a["Andrew"] = "C49"
  • a["Ken"] = "D52"

You can also declare it and add some elements to it at once:

  • a = {"Andrew": "C49, "Ken": "D52"}
hash
keyvalue
AndrewC49
SallyC46
KenD52
GordonC49

Telephone book

When we create the structure we just need to use the curly-braces notation.

We can look up the phone number for "Sally" using the array key.

[Font] [Default] [Show] [Resize] [History] [Profile]

Missing items

You need to be sure that the key is in the associative array before you try to access it.

In this example we try to retrieve an entry that isn't in the list.

Before that we use the in operator to test if the key exists.

[Font] [Default] [Show] [Resize] [History] [Profile]

Getting all values back

Commonly we want to loop over all of the keys in the associative array.

The method .keys() permits this. We can also use .values().

The method .items() returns a

list of pairs of keys and values.

[Font] [Default] [Show] [Resize] [History] [Profile]

Getting keys back in the right order

The keys come back in an unpredictable order. However we can sort them.

[Font] [Default] [Show] [Resize] [History] [Profile]

See also