Home Micropython Python Basics : Dictionary

Python Basics : Dictionary

by shedboy71

A dictionary is a data type that holds key-value pairs. These key-value pairs are called items. You will sometimes hear dictionaries referred to as associative arrays, hashes, or hash tables.

Dictionaries are created using comma-separated items between curly braces. The item starts with a key, is then followed by a colon, and is concluded with a value. The format is dictionary_name = {key_1: value_1, key_N: value_N} .

To create an empty dictionary use: dictionary_name = {}.

Items in a dictionary can be accessed by key. To do so, enclose the key in a bracket immediately following the dictionary name. The format is dictionary_name[key] .

There are a couple of important points while using dictionary keys

  • More than one entry per key is not allowed ( no duplicate key is allowed)
  • While the values in the dictionary can be of any type the keys must be immutable like numbers or strings.
  • Dictionary keys are case sensitive – If you were to create a similarly named key but you use a different case then these are treated as different keys in Python.

Let’s look at an example

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}

 

Accessing Values in Dictionary

To access an element in a dictionary, you can use square brackets along with the key to obtain its value.

Let’s take a look at this

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

When run you will see something like this

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> dict['Name']: Bill
dict['Age']: 59
dict['Country']: UK

Update A Dictionary

To update a dictionary you can simply add a new entry or a key-value pair, modify an existing entry, or delete an existing entry.

Let’s see an example of this.

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

dict['Age'] = 60; # update existing entry
dict['Country'] = 'USA'; # update existing entry
dict['City'] = 'New York'; #add a new entry

print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])
print ("dict['City']: ", dict['City'])

When run this would look like this

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> dict['Name']: Bill
dict['Age']: 59
dict['Country']: UK
dict['Name']: Bill
dict['Age']: 60
dict['Country']: USA
dict['City']: New York

Check if a Key Exists

To check if a specified key is present in a dictionary you use the in keyword.

Let’s see an example of this.

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

if "Country" in dict:
  print("Key is in the dictionary")

 

Length of a Dictionary

To determine how many items a dictionary has you can use the len() method.

Let’s see an example of this.

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

print(len(dict))

 

Removing Items from a Dictionary

There are several methods to remove items from a dictionary:

You can use the pop() method to remove the item with the key name that you specify

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

dict.pop("Country")
print(dict)

You can use the popitem() method to remove the last inserted item from Python 3.7.0 onwards, previous to this version of python it would remove a random item

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

dict.popitem()
print(dict)

The del keyword can either remove the item with the specified key name or it can delete the dictionary completely

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

del dict["Country"]
print(dict)

and to delete the entire dictionary, if you try and print or access this after you delete the entire dictionary you will see an error

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

del dict

You can use the clear() method to empty a dictionary.

dict = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
print ("dict['Country']: ", dict['Country'])

dict.clear()
print(dict)

 

Copying a dictionary

There are a couple of methods that allow you to make a copy of a dictionary.

You can use the copy() method and the built-in method dict()

dict1 = {'Name': 'Bill', 'Age': 59, 'Country': 'UK'}
print ("dict1['Name']: ", dict1['Name'])
print ("dict1['Age']: ", dict1['Age'])
print ("dict1['Country']: ", dict1['Country'])

dict2 = dict1.copy()
print(dict2)
dict3 = dict(dict1)
print(dict3)

Run this and you will see something like this

 
MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> dict['Name']: Bill
dict['Age']: 59
dict['Country']: UK
{'Name': 'Bill', 'Country': 'UK'}

You may also like