MicroPython ‘dictionary’ Data Type

Contents

Introduction

MicroPython is a “slim” version of Python specifically designed with a small footprint to efficiently run on memory constrained microcontrollers.

Computer languages have a built-in set of data types along with user capability to define custom types. MicroPython is no exception. The built-in data types for MicroPython:

  • Numeric
  • Boolean
  • Sequence Type
  • Set
  • Dictionary
Python data type hierarchy
FIG 1 - Source: geeksforgeeks.org

The python dictionary can also be considered a collection type

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable.
  • Tuple is a collection which is ordered and unchangeable.
  • Set is a collection which is unordered, unchangeable and unindexed.
  • Dictionary is a collection which is ordered[1] and changeable.

Dictionary Definition

A MicroPython dictionary is similar to a MicroPython list. The main difference is the manner used to access elements with list elements by index and dictionary elements by key.

  • Dictionaries and lists are mutable. This means that existing elements can be altered (changed).
  • Dictionaries and lists are dynamic. They can grow or shrink in size.
  • Dictionaries and lists can be nested. A list can be an element in another list. An element within a dictionary may be another dictionary or even a list. A dictionary might also be a dictionary of other dictionaries.
  • While list elements are accessed by index (their position in the list), dictionary elements are accessed by keys.

A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

A dictionary can be defined by enclosing a comma-separated list of key-value pairs in curly braces { }. A colon : separates each key from its associated value. A dictionary can also be created with the dictionary function (constructor) dict().

Example 1

# Different ways to define dictionaries.

# Direct assignment
d1 = {'Color' : 'blue', 'Doors' : 4}
print('d1 =', d1)

# Convert list to dictionary with dict()
d2 = dict([('Color', 'red'), ('Doors', 2)])
print('d2 =', d2)

# Another way to use dict()
d3 = dict(Color = 'brown', Doors = 3)
print('d3 =', d3)

# Empty dictionary
d4 = {}
print('d4 =', d4)

# Dictionary of dictionaries
all = {1 : d1,
       2 : d2,
       3 : d3}
print('all =', all)
          
Output:

d1 = {'Color': 'blue', 'Doors': 4}
d2 = {'Color': 'red', 'Doors': 2}
d3 = {'Color': 'brown', 'Doors': 3}
d4 = {}
all = {3: {'Color': 'brown', 'Doors': 3}, 
       1: {'Color': 'blue', 'Doors': 4},
       2: {'Color': 'red', 'Doors': 2}}
          

Accessing the Dictionary

As noted above dictionary entries are not accessed with an index. Rather, by using the key enclosed in square brackets [ ] it will reference the associated value. An error (exception) will be raised if the key doesn't exist within the dictionary. A MicroPython tutorial on exception handling can be found here.

Example 2

          # Accessing dictionary elements.

# Defining some dictionaries
d1 = {'Color' : 'red', 'Doors' : 4}
d2 = dict([('Color', 'green'), ('Doors', 2)])
d3 = dict(Color = 'brown', Doors = 3)

# Get value from each dictionary
# where the key = 'Color'.
print(d1['Color'], d2['Color'], d3['Color'])
print()

# Attempting to access a dictionay key
# that doesn't exist will throw an error.
print(d1['Tyres'])

          
Output from the micro:bit

red green brown

Traceback (most recent call last):
  File "main.py", line 15, in <module>
KeyError: Tyres

          

The request for the value of key 'Tyres' from dictionary d1 returns a KeyError exception as this key doesn't exist in the dictionary.

The following code snippet is a much more in-depth dictionary example where all elements of a dictionary are also dictionaries. Additionally, each nested dictionary also contains a list.

Example 3

# Example of nested dictionaries.

# Each value of the dictionary 'towns' is another dictionary,
# i.e. dictionaries nested within a parent dictionary.

towns = {'Hampton' : {'country' : 'UK', 'av_age' : 35.9, 'climate' : ['26', 'humid']},
         'Clayton' : {'country' : 'USA', 'av_age' : 29.3,'climate' : ['19', 'dry']},
         'Sanyun'  : {'country' : 'Korea', 'av_age' : 18.4,'climate' : ['12', 'wet']}}

# Return some statistics from the 'towns' dictionary      
print("Average age of Clayton's population is", towns['Clayton']['av_age']) 
print("Sanyun's average temperature is", towns['Sanyun']['climate'][0])

          
Output:

Average age of Clayton's population is 29.3
Sanyun's average temperature is 12
          

Adding, Updating and Deleting Entries to a Dictionary

Adding an entry to an existing dictionary is simply a matter of assigning a new key and value.

An existing entry can be updated by assigning a new value to an existing key.

Example 4

# Adding & updating entries in a dictionary

# Define a dictionary
dict1 = {'Color' : 'red', 'Doors' : 4}
print('Before:', dict1)
print()

# Add the key 'tyres' to the dictionary
dict1['Tyres'] = 'Dunlop'

# Change the value of the key 'color'
# from 'red' to 'yellow'
dict1['Color'] = 'yellow'

# Verify the changes
print('After:', dict1)

            
Output:

Before: {'Color': 'red', 'Doors': 4}

After: {'Color': 'yellow',
        'Doors': 4,
        'Tyres': 'Dunlop'}
            

A dictionary entry can be deleted by specifying the key in conjunction with the del statement.

Example 5

# Delete a dictionary entry

dict1 = {'Color' : 'red', 'Doors' : 4}

del dict1['Color']
print(dict1)

            
Output:

{'Doors': 4}
            

Dictionary Membership

Attempting to access a dictionary value by a key that doesn't exist within the dictionary will cause an exception to be raised. This can be circumvented by using the in operator. If the key is found in the dictionary then True is returned otherwise False. The operator not in> works inversely.

Example 6

# Using the operators 'in' and 'not in'
# to guard against an exception being
# raised when accessing a dictionary
# with a key that doesn't exist.

# Define a dictionary
dict1 = {'Color' : 'red', 'Doors' : 4}

# Use operator 'in' to check
# that key 'Tyre' exists before attempting
# to access its associated value.
if ('Tyre' in dict1):
    print("'Tyre' is", dict1['Tyre'])
else:
    print("No entry for 'Tyre' found")

# Use operator 'not in' to check whether
# the key 'Color' exists in the dictionary.
if ('Color' not in dict1):
    print("No entry for 'Color' found")
else:
    print("'Color' is", dict1['Color'])
            
Output:

No entry for 'Tyre' found
The value of 'Color' is red
            

Dictionary Functions

Table 1: MicroPython dictionary Functions
Function Description
len()

Returns the number of key:value pairs in a dictionary.

len({'Color' : 'red',
     'Doors' : 4})
⇒ 2

max()

Returns the maximum key or value in a dictionary.

d = {'Color':'red', 'Doors':'four'}
max(d.keys()) ⇒ 'Doors'
max(d.values()) ⇒ 'red'

min()

Returns the minium key or value in a dictionary.

d = {'Color':'red', 'Doors':'four'}
min(d.keys()) ⇒ 'Color'
min(d.values()) ⇒ 'four'

sorted(item
  [, reverse =
  True|False])

Returns a list of sorted dictionary keys.

d1 = {'Tyres' : 'Dunlop',
      'Color' : 'red',
      'Doors' : 4}

sorted(d1)
⇒ ['Color', 'Doors', 'Tyres']

sorted(d1, reverse = True)
⇒ ['Tyres', 'Doors', 'Color']

Dictionary Methods

Table 2: MicroPython dictionary Methods
Method Description
update(obj)

Merges dictionary with another dictionary or key/value pair(s).

d1 = {'A' : 4, 'B' : 7}
d2 = {'B' : 5.8, 'C' : 9}

d1.update(d2)
print(d1)
⇒ {'A': 4, 'C': 9, 'B': 5.8}

get(key [,
       default])

Returns the value for a key if it exists in the dictionary. If a default value is given, it is returned if the key isn't found.

d1 = {'Tyres' : 'Dunlop',
     'Color' : 'red',
     'Doors' : 4}

d1.get('Color') ⇒ 'red'
d1.get('Wheels', -1) ⇒ -1

items()

Returns a list of key-value pairs in a dictionary.

d1 = {'Tyres' : 'Dunlop',
     'Color' : 'red',
     'Doors' : 4}

d1.items() ⇒ dict_items([('Doors', 4),
     ('Tyres', 'Dunlop'),
     ('Color', 'red')])

keys()

Returns a list of keys in a dictionary.

d1 = {'Tyres' : 'Dunlop',
     'Color' : 'red',
     'Doors' : 4}

d1.keys()
⇒ dict_keys(['Doors', 'Tyres', 'Color'])

values()

Returns a list of values in a dictionary.

d1 = {'Tyres' : 'Dunlop',
     'Color' : 'red',
     'Doors' : 4}

d1.values()
⇒ dict_values([4, 'Dunlop', 'red'])

pop(key [,
       default])

Removes a key from a dictionary and returns its value. If a default value is given, it is returned if the key isn't found.

d1 = {'Tyres' : 'Dunlop',
     'Color' : 'red',
     'Doors' : 4}
value = d1.pop('Tyres')

print(value) ⇒ Dunlop
print(d1)
⇒ {'Doors': 4, 'Color': 'red'}

d2 = {'A' : 4, 'B' : 7}
value = d2.pop('C', -1)

print(value) ⇒ -1
print(d2)
⇒ {'B': 7, 'A': 4}

popitem()

Removes a random key-value pair and returns it as a tuple.[2]

d1 = {'A' : 1, 'B' : 2}
d1['C'] = 3
print(d1)
⇒ {'A': 1, 'C': 3, 'B': 2}

popped = d1.popitem()
print(popped) ⇒ ('A', 1)

print(d1)
⇒ {'C': 3, 'B': 2}

clear()

Deletes all entries in a dictionary.

d1 = {'A' : 4, 'B' : 7}
d1.clear()
print(d1) ⇒ {}

copy()

Creates a copy of a dictionary.

d1 = {'A' : 4, 'B' : 7}
d2 = d1.copy()
print(d1) ⇒ {'A': 4, 'B': 7}
print(d2) ⇒ {'A': 4, 'B': 7}

setdefault(
  keyname,
  value)

Returns the value of the item with the specified key. If the key does't exist, the key is inserted with the specified value.

d = {'x' : 4, 'y' : 7}
x = d.setdefault('z', 2)
print(d)
⇒ {'y': 7, 'x': 4, 'z': 2}
print(x) ⇒ 2

dict.fromkeys(
  keys,
  [value])

Returns a dictionary from a given sequence of keys. If the optional value is supplied, all the keys will be assigned this value.

L = ['x', 'y']
d1 = dict.fromkeys(L)
print(d1)
⇒ {'y': None, 'x': None}

d2 = dict.fromkeys(L, 5)
print(d2)
⇒ {'y': 5, 'x': 5}