Home      |       Contents       |       About

Prev: The 'dictionary' object       |       Next: Dictionary & List combinations

Dictionary construction

  • Three ways for constructing a dictionary are explained below:
    • Assigning pairs
    • Calling the dict() constructor method
    • dict comprehension

(1) Assigning pairs

  • Pairs can be added to a dictionary by assigning new values to keys. The dictionary should be initialized as empty using the curly brackets notation
In [1]:
di = {}
di['ES'] = 'Spain'
di['GR'] = 'Greece'
di['IT'] = 'Italy'
di
Out[1]:
{'ES': 'Spain', 'GR': 'Greece', 'IT': 'Italy'}
  • This is usually implemented as a simple way to add new pairs to a dictionary

(2) Using the dict() constructor method

  • The dict() method is the 'constructor' of dictionaries (similarly to list, int, float, str that we already used)
  • The dict() method requires as arguments the pair-elements of the dictionary. This can be accomplished in many ways, the most common are presented below.
  • List of pairs (tuples)
    A list containing as elements the dyads (tuples) is passed to the dict() method
In [2]:
alist = [('ES','Spain'),('GR','Greece'),('IT','Italy')]
di = dict(alist)
di
Out[2]:
{'ES': 'Spain', 'GR': 'Greece', 'IT': 'Italy'}
In [3]:
alist = [(chr(i),i) for i in range(65,70)]
di = dict(alist)
di
Out[3]:
{'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69}
  • Assignment
    Assignments linking keys to values can be passed to the dict() method. Observe that the keys are passed in dict() as simple names (not strings enclosed in quotes)
In [4]:
di = dict(ES='Spain',GR='Greece',IT='Italy')
di
Out[4]:
{'ES': 'Spain', 'GR': 'Greece', 'IT': 'Italy'}
  • zip() two iterables
    The zip() method accepts two iterables (for example two lists or one list and one string) and returns a 'zip' object which is a binding in pairs of the iterable elements. When this zip object is passed to dict() a dictionary is returned.
In [5]:
code =['ES','GR','IT']
country = ['Spain','Greece','Italy']

di = dict(zip(code,country))
di
Out[5]:
{'ES': 'Spain', 'GR': 'Greece', 'IT': 'Italy'}

(3) Dictionary comprehension

  • The general pattern for writing a dict comprehension is:
      di = {<key expression:value expression> <'for' loop(s)>}
In [29]:
di = {x:x**2 for x in range(10)}
di
Out[29]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
In [32]:
di = {str(x):x for x in range(5)}
di
Out[32]:
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
In [9]:
di = {str(x*y):x+y for x in range(2) for y in range(3)}
di
Out[9]:
{'0': 1, '1': 2, '2': 3}
In [22]:
di = {i if i%2==0 else 1:chr(x) if i%2==0 else 0 for i,x in enumerate(range(65,80,2))}
di
Out[22]:
{0: 'A', 1: 0, 2: 'E', 4: 'I', 6: 'M'}
In [37]:
keys = ['a','b','c','d','e']
vals = ['A','B','C','D','E']
di = {keys[i]:vals[i] for i in range(5)}
di
Out[37]:
{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}

Conditional expressions in dict comprehensions

  • Each of "key expression" and "value expression" can be a conditional expression in itself. This allows to describe complex forms of dictionaries in a most elegant and efficient way.
  • In the example below the dict comprehension uses pow() function to map integer keys onto their power 2 values
In [6]:
di = {i : pow(i,2) for i in range(10)}
di
Out[6]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
  • The following example uses conditional expression to map integer keys onto power 2 (if key<=4) or 3 (if key>4)
In [8]:
di = {i : pow(i,2) if i<=4 else pow(i,3) for i in range(10)}
di
Out[8]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
  • This last example, uses conditional expression for both keys and values and changes also the type of the key (integer if key<=4, string if K>4
In [9]:
di = {i if i<=4 else str(i) : pow(i,2) if i<=4 else pow(i,3) for i in range(10)}
di
Out[9]:
{0: 0,
 1: 1,
 2: 4,
 3: 9,
 4: 16,
 '6': 216,
 '8': 512,
 '9': 729,
 '7': 343,
 '5': 125}
In [1]:
di = {i:j for i,j in {1:'a', 2:'b'}.items()}
di
Out[1]:
{1: 'a', 2: 'b'}

. Free learning material
. See full copyright and disclaimer notice