Main Content

Setting up and using a dict in Python - simple first example

Archive - Originally posted on "The Horse's Mouth" - 2015-01-30 08:14:17 - Graham Ellis

Here's a very short and easy example of the use of a dict in Python.

Set up a dict and fill it from a file (key value is 2nd field; value to be looked at is 7th)

  lookup = {}
  for record in open("railstats.txt","r"):
    fields = record.strip().split('\t')
    tlc = fields[1]
    name = fields[6]
    lookup[tlc] = name


You can't sort a dict - but you CAN sort a list of the keys

  codes = lookup.keys()
  codes.sort(lambda a,b: cmp(lookup[b],lookup[a]))


And you can then list the elements in the order of the list

  for code in codes:
    print code,lookup[code])


Complete code [here].

It's all very well looking at what a program does - but would you know how to decide how to write it like this? Our Pyton Programming courses will teach you. Follow our course schedule link if you'ld like to come - at the time of writing, I'm actually presenting a private course, there's another private course at the end of next month (February) and then there's a public course starting on 2nd March 2015, but the diary is updated if you've found this page on our archive, and we have dates available (from mid March) for private courses.