Python dictionary for quick look ups
Archive - Originally posted on "The Horse's Mouth" - 2007-04-12 06:46:10 - Graham EllisUsing a dictionary in Python, you can avoid the need for a loop in your program to search out elements in a collection. Suppose, for example, you have a list of people and a list of their countries of origin, you could look up individuals like this:
names = ["Jesus","Marc","Michal","Graham"]
places = ["Spain","USA","Poland","UK"]
for x in range(len(names)):
if names[x] == "Marc": print places[x]
if names[x] == "Graham": print places[x]
But with a dictionary, it is both easier and faster:
who = {"Jesus":"Spain", "Marc":"USA", "Michal":"Poland","Graham":"UK"}
print who["Michal"]
print who["Jesus"]
In effect, a dictionary is a database table with two columns ...