Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

2.9 Dictionaries

Dictionaries (or “dicts” for short) are Python’s mapping type and work like associative arrays or hashes found in Perl; they are made up of key-value pairs. Keys can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dicts are enclosed by curly braces ( { } ).

>>> aDict = {'host': 'earth'} # create dict
>>> aDict['port'] = 80        # add to dict
>>> aDict
{'host': 'earth', 'port': 80}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'earth'
>>> for key in aDict:
...  print key, aDict[key]
...
host earth
port 80

Dictionaries are covered in Chapter 7.

  • + Share This
  • 🔖 Save To Your Account