Python - Dictionaries and Sets

Dictionaries in Python are Mongo DB document objects

Mongo DB collection's document model is a binary representation of a JSON document. It's called BSON.
Mongo DB Link BSON Link

Fortunately for us, Python's dictionary data structure is essentially a JSON document, grouped by key-pair-values, which makes reading and modifying data in Mongo DB and breeze in Python.

Let's take a quick look at the document model in a sample collection called names.

In the Mongo DB shell

MongoDB shell version: 3.0.5
connecting to: test
> show dbs
admin  0.078GB
local  0.078GB
m101   0.078GB
reddit 0.078GB
test   0.078GB
> show collections
> db.names.find().pretty();
  "_id" : ObjectID("55d4dbf500902f4ad58298ce"),
  "name" : "Monty Python",  
  "address" : {
    "street" : "1234 Main Street",
    "city" : "New York",
    "state" : "NY",
    "zip_code" : "10012"
  "username" : "",
  "password" : "+41$^&*)_*(*@#%&*)",
  "role" : "admin",  

That should look pretty familiar to us Python students. In the Python shell, I created this quick dictionary called contact_names.

>>> contact_names = {'Roger' : 555-1212, 'Beth' : 555-2323, 'Karen' : 555-3434}
>>> contact_names['Samantha'] = 555-5151
>>> contact_names
{'Roger' : 555-1212, 'Beth' : 555-2323, 'Karen' : 555-3434, 'Samantha' : 555-5151}
>>> contact_names['Beth']
>>> contact_names.keys()
{'Roger', 'Beth', 'Karen', 'Samantha'}
>>> del contact_names['Roger']
>>> contact_names['Marc'] = 555-9876
>>> contact_names
{'Beth' : 555-2323, 'Karen' : 555-3434, 'Samantha' : 555-5151, 'Marc' : 555-9876}
>>> 'Samantha' in contact_names

Simple Key Value Pairs

You can also create dictionaries using the dict() constructor directly from key-value pairs:

# Python will create a dictionary object from this command
>>> dict([('Roger', 555-1212), ('Beth', 555-2323), ('Kim', 555-9898)])
{'Roger' : 555-1212, 'Beth' : 555-2323, 'Kim' : 555-9898}

We'll be consuming these types of objects in later posts as we build our sample applications.

What I like about these simple data structures is the ability to quickly and effectively access and modify these values.

>>> dict1 = {}
>>> dict1['a'] = 'Alpha One'
>>> dict1['b'] = 'Bravo Two'
>>> dict1['c'] = 'Charlie Six'
>>> print(dict1)
{'a' : 'Alpha One', 'b' : 'Bravo Two', 'c' : 'Charlie Six'}
>>> dict1['c'] = "Delta Four"
>>> dict['d'] = "Echo Eight"
>>> print(dict1)
{'a' : 'Alpha One', 'b' : 'Bravo Two', 'c' : 'Delta Four', 'd' : 'Echo Eight'}
>>> dict1['b']
'Bravo Two'
>>> if 'a' in dict1:
>>>   print(dict1.get['a'])
'Alpha One'
>>> for k, v in dict1.items():
>>>   print(key, v)
a Alpha One
b Bravo Two
c Delta Four
d Echo Eight
>>> for key in sorted(dict.keys(), reverse=True):
      print(key, dict[key])
d Echo Eight
c Delta Four
b Bravo Two
a Alpha One

More Dictionary Functions

Dictionary Formatting

The % operator works conveniently to substitute values from a dictionary into a string by name:

>>> my_hash = {}
>>> my_hash['the_count'] = 152
>>> my_hash['the_type'] = "insert"
>>> my_hash['the_db'] = 'pythonSampleDB'
>>> s = 'The database retrieved %(the_count)c records of type %(the_type)t from %(the_db)d.' % my_hash
'The database retrieved 152 records of type insert from pythonSampleDB.'

Delete Items from the Dictionary

The del operator does deletions of items and not just from dictionaries, but from variable instance name, list or set. In the most simple cases, it removes the definition of a variable. Del can also be used on list elements or slices to delete that part of the list. And it can also remove an item from a dictionary.

>>> my_var = 16
>>> del my_var  # my_var no longer a stored value
>>> my_list = ['a', 'b', 'c', 'd']
>>> del my_list[0]     ## Delete first element
>>> del my_list[-2:]   ## Delete last two elements
>>> print(list)        ## ['b']
>>> dict = {'a': 1, 'b': 2, 'c': 3}
>>> del dict['b']      ## Delete 'b' entry
>>> print(dict)        ## {'a':1, 'c':3}

Sets in Python

Python includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses of the set data structure is for testing membership in a list or removing duplicate entries in a list or tuple.

Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Please note: to create an empty set you have to use set(), not variable = {}; which simply creates an empty dictionary.

>>> fruit_basket = ['apple', 'banana', 'pear', 'orange', 'cranberry']
>>> grocery_list = set(fruit_basket)
>>> grocery_list
set(['apple', 'banana', 'pear', 'orange', 'cranberry'])
>>> 'apple' in grocery_list
>>> 'grapes' in grocery_list

Another cool feature is set comprehensions. Like list comprehensions, you can make your code very simple.

>>> r = {x for x in 'python' if x not in 'pn'}
>>> r
set([y, t, h, o])
>>> 'y' in r
>>> 'n' in r

Craig Derington

Secular Humanist, Libertarian, FOSS Evangelist building Cloud Apps developed on Red Hat Enterprise Linux and Ubuntu Server. My toolset includes Python, Celery, Flask, Django, MySQL, MongoDB and Git.

comments powered by Disqus