Home      |       Contents       |       About

Prev: -       |       Next: Constructing dictionaries

The 'dictionary' object

'dictionary'

  • A dictionary (or shortly: a 'dict') is a mapping structure: it contains 'key:value' pairs which map key objects onto value objects
  • Usually keys are strings (can be integers too) and so a dictionary supports string-based indexing (and not only integer-based as in lists)
  • Dictionary pairs are written enclosed in curly brackets, however when using a key to refer to a value we use square brackets (like a list)
  • In the example below, 'GR' is a key and 'Greece' the respective value
In [1]:
di = {'GR':'Greece', 'IT':'Italy', 'ES':'Spain'}
di['GR']
Out[1]:
'Greece'

Dictionary features

  • A dictionary is:
    • mapping: a dictionary is usually described as a 'mapping' structure, meaning that it establishes a mapping of keys on values
    • collection: a dict is considered as a 'collection' of items in contrast to a list which is considered as a sequence
    • indexed: a dictionary is an indexed object with keys as indexes
In [2]:
di = {'GR':'Greece', 'IT':'Italy', 'ES':'Spain'}
print(di['GR'], di['IT'], di['ES']) 
Greece Italy Spain
  • unordered: a dictionary can not be put in any specific order; ordering/sorting a dictionary is meaningless. Pairs of a dictionary can be written in any order and appear also in any order (when printed) . Ordering (sorting, etc.) pairs in a dictionary is meaningless
In [3]:
di = {'IT':'Italy', 'ES':'Spain', 'GR':'Greece'}
di
Out[3]:
{'ES': 'Spain', 'GR': 'Greece', 'IT': 'Italy'}
  • iterable: When used in a for loop a dictionary can return either its keys or key:value pairs to the iterator(s)
In [4]:
# dictionary keys returned to the iterator
di = {'IT':'Italy', 'ES':'Spain', 'GR':'Greece'}
for code in di:
    print(di[code], end=' ')
Spain Italy Greece 
  • mutable: dictionary elements can be altered 'in place' (without creating a new copy of a dictionary)
In [5]:
di = {'IT':'Italy', 'ES':'Spain', 'GR':'Greece'}
di['ES'] = 'España'
di['GR'] = 'Hellas'
di
Out[5]:
{'ES': 'España', 'GR': 'Hellas', 'IT': 'Italy'}
  • heterogeneous: dictionary keys should be IMMUTABLE objects (for example: strings or numerics) while values can be of any type
In [20]:
L1 = ['A','B','C','D','E']
di = {'Uno':'Ένα', 1:L1, 20.35:L1[2:4]}

print(di[20.35], di[1], di['Uno'])
['C', 'D'] ['A', 'B', 'C', 'D', 'E'] Ένα
  • The 'dictionary' objects when combined with lists provide the basis for advanced complex and powerful data representations

Dictionary indexing and assignment

  • A dictionary is a unordered collection of pairwise items: len() returns the number of pairwise items of the dict
In [21]:
di = {1:'uno', 'two':'dos', '3':'tres'}
len(di)
Out[21]:
3

See a pythontutor visualization of the above dict

  • The dictionary keys are indexes to associate values
In [22]:
di = {1:'uno', 'two':'dos', '3':'tres'}
print(di[1], di['two'])
uno dos
  • Values can be of any type (lists and other dicts included)
In [11]:
di = {1:[1,2,3], 'two':'2', '3':{'three':'tres'}}
print(di[1], di['3'])
[1, 2, 3] {'three': 'tres'}

keys() and values()

  • Keys and values can be easily extracted as lists with the keys() and values() methods
  • Note that di.keys() and di.values() are passed as arguments to the list() constructor method
In [6]:
di = {'GR':'Greece', 'IT':'Italy', 'ES':'Spain'}

print(list(di.keys()))

print(list(di.values()))
['ES', 'IT', 'GR']
['Spain', 'Italy', 'Greece']
  • You can add new pairs with simple assignments
In [7]:
di = {'GR':'Greece', 'IT':'Italy', 'ES':'Spain'}
di['ML'] = 'Malta'
di['FR'] = 'France'
di
Out[7]:
{'ES': 'Spain', 'FR': 'France', 'GR': 'Greece', 'IT': 'Italy', 'ML': 'Malta'}
  • ...or delete pairs with the del command
In [8]:
di = {'GR':'Greece', 'IT':'Italy', 'ES':'Spain'}
del di['IT']
di
Out[8]:
{'ES': 'Spain', 'GR': 'Greece'}

Dictionary is 'mutable'

(like a list)  
  • A dict is a mutable object and you can change a value 'in place' (no copy)
In [26]:
di = {'1':'one', '2':'two'}
di['1'] = 'uno'
print(di)
{'2': 'two', '1': 'uno'}
  • Be careful with shared object reference in mutable dictionaries
In [27]:
# di1 and di2 names reference the same dict object in memory  
di1 = {'1':'one', '2':'two', '3':'three'}
di2 = di1
di2['2'] = 'dos'
print(di1)
{'3': 'three', '2': 'dos', '1': 'one'}

Dictionary as iterable in a 'for' loop

  • A dictionary is iterable structure and can be used as an iterable in the 'for' loop command. In such a case you should remember the following:
    • a) Only the keys are returned to the iterator with no specific order. Thus the logic of the loop should not be based on any particular order of keys
In [28]:
zoo = {'lion':3,'tiger':2,'elephant':5}
for animal in zoo:
    print(animal)
lion
tiger
elephant
  • b) In case we need both keys and values we can call the items() method
In [9]:
# dictionary key:value pair returned to the iterators code and name
di = {'IT':'Italy', 'ES':'Spain', 'GR':'Greece'}
for code, name in di.items():
    print(code, 'Country name: ', name)
ES Country name:  Spain
IT Country name:  Italy
GR Country name:  Greece
  • We can use one iterator with the items mehotd. In this case the iterator is constructed as a tuple (see the 'tuple' section for more explanations)
In [10]:
di = {'IT':'Italy', 'ES':'Spain', 'GR':'Greece'}
for country in di.items():
    print('Code = ', country[0], '\tCountry name: ', country[1])
Code =  ES 	Country name:  Spain
Code =  IT 	Country name:  Italy
Code =  GR 	Country name:  Greece

The 'in' operator

  • The 'in' operator in a dictionary (like in lists and strings) is used to test for 'membership', that is, examine whether a key is included in dictionary
In [11]:
di = {'GR':'Greece', 'IT':'Italy', 'ES':'Spain'}
if 'FR' in di:
    print('Country name: ', di['FR'])
else:
    print('No such country in di')
No such country in di

. Free learning material
. See full copyright and disclaimer notice