Dictionaries

A dictionary is a fancy list
  • A dictionary consists of (key,value) pairs

  • The key is an immutable type(e.g. a number, a string, a tuple)

  • The value can be anything

  • We retrieve the value in a dictionary by using the associated key

  • Dictionaries are fancy lists that are not restricted to consecutive integers for indexing

  • We create dictionaries with curly braces { }

  • We assign elements to and retrieve elements from dictionaries with square brackets [key]

In [1]: emails={}

In [2]: emails['Duan']='[email protected]'

In [3]: emails['Charlie']='[email protected]'

In [4]: emails['Stuart']='[email protected]'

In [5]: emails['Allen']='[email protected]'

In [6]: emails.keys()
Out[6]: ['Allen', 'Charlie', 'Duan', 'Stuart']

In [7]: emails.values()
Out[7]: ['[email protected]', '[email protected]', '[email protected]', '[email protected]']

In [8]: emails
Out[8]: 
{'Charlie': '[email protected]',
 'Duan': '[email protected]',
 'Allen': '[email protected]',
 'Stuart': '[email protected]'}

In [9]: emails['Duan']
Out[9]: '[email protected]'
  • Dictionaries can be constructed from a list of (key,value) pairs (or 2-turples)from two matching lists or keys and values

In [10]: instructors=['Duan','Charlie','Stuart','Allen']

In [11]: email=['[email protected]','[email protected]','[email protected]','[email protected]']

In [12]: adict=dict(zip(instructors,email))

In [13]: adict
Out[14]: 
{'Charlie': '[email protected]',
 'Duan': '[email protected]',
 'Allen': '[email protected]',
 'Stuart': '[email protected]'}

Last updated

Was this helpful?