Python Dictionaries

Dictionaries are called hashes or associative arrays in PHP and Perl. They are unordered set of key-value pairs. Lists have numerical indices. In a dictionary, the index is called a key and the key is always a string.

version = {'Python': 3, 'Perl': 6}

# add a key-value pair to the dictionary
version['PHP'] = 5
print version
# {'Python': 3, 'PHP': 5, 'Perl': 6}

# remove a key-value pair
del version['Perl']
# {'Python': 3, 'PHP': 5}

# print all the keys
print version.keys()
# ['Python', 'PHP']

# print all values
print version.values()
# [3, 5]

# does the key exist
print 'PHP' in version
# True

# looping through the dictionary
for k, v in version.iteritems():
	print 'I installed ', k, v
# I installed Python 3
# I installed PHP 5

# enumerating a dictionary
for i, v in enumerate(['Junk', 'Jan', 'Feb', 'Mar']):
	print i, v
# 0 Junk
# 1 Jan
# 2 Feb
# 3 Mar

# zip() function allows you to loop over multiple sequences
names = ['Alice', 'Bob', 'Carla']
dob = ['Jan 1, 2001', 'Feb 2, 2002', 'Mar 3, 2003']
lives = ['Australia', 'Belgium', 'Canada']
for a, b, c in zip(names, dob, lives):
	print  '{0} was born on {1} in {2}' . format(a, b, c)
# Alice was born on Jan 1, 2001 in Australia
# Bob was born on Feb 2, 2002 in Belgium
# Carla was born on Mar 3, 2003 in Canada