Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!


Dictionaries or Associative Arrays in Python

I have a couple previous articles around a similar topic but since I have not added any python code here is a short how to for future reference. It may be called associative arrays in other languages but Python calls it dicts or dictionaries.

Related links:

Manually constructing the dictionary:

mailLists = {}
mailLists['dba'] = ['joe', 'jim', 'jeff', 'john']
mailLists['sa'] = ['mike', 'matt' ]

#print mailLists

#for key in mailLists:
#  print key

print mailLists['dba']
print mailLists['sa']

for k,v in mailLists.iteritems():
  print k + ": " + str(v)

For me the real value in this is for example when you build the lists. Think looping through an input file with lines like this:
jon : dba

Now you add jon to the array with key 'dba'. If the key does not exist we simply add one. If the key exists a new item is added to it.

mailLists = {}

with open('b.txt') as input_file:
  for i, line in enumerate(input_file):
    #print line,
    v,k = line.strip().split(':')
    k = k.strip()
    if k not in mailLists.keys():
      mailLists[k] = []

for k,v in mailLists.iteritems():
  print k + ": " + str(v)
# python b.py
dba: ['jon ', 'jeff ']
sa: ['matt ']


Bio Info for Riaan