Skip to content

Dictionaries or associative arrays in python

wordpress meta

title: 'Dictionaries or Associative Arrays in Python'
date: '2015-01-15T10:11:33-06:00'
status: publish
permalink: /dictionaries-or-associative-arrays-in-python
author: admin
excerpt: ''
type: post
id: 815
category:
    - Python
tag: []
post_format: []

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:
http://blog.ls-al.com/creating-a-javascript-array-with-one-to-many-type-relationship/
http://blog.ls-al.com/multi-array-in-bash/
http://blog.ls-al.com/multidimensional-array-in-python/

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] = []
    mailLists[k].append(v)

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