Python Data Structures: Dictionary, A Prelude to MapReduce


Dictionaries are useful for easy access to key:value pairs.

Unlike lists, dictionaries are mutable, mapping objects.

They are hashable; meaning indexed by keys, which point to values. Strings, numbers, and tuples(when immutable) can be used in the data structure.

Creating an empty dictionary object:

dictionaryName = {}

However, to do anything useful, you’ll want to do this with the intent of filling the empty object.

Explicitly build your object:

dictionaryName = {"Key1":1, "Key2":2, "Key3":3}

This will create a dictionary containing keys ‘Key1, Key2, Key3’ and their associated with values of ‘1, 2, 3’.

Dictionaries are natively unsorted, each time you call the dict, you will get a random output of the key:value pairs.

However, you can use the sorted() command to force an ordering to your output based on values.

Sorting by value:

dictionaryName = {"Key1":1, "Key2":2, "Key3":3}

sortYourList = sorted((key,value) for (key,value) in dictionaryName.items())

print(sortYourList)

[Output]
”[(‘Key1’, 1), (‘Key2’, 2), (‘Key3’, 3)]”

Iterative access:

So, let’s say you want to loop through the contents of your dict to analyze what’s present…

Using the general pythonic model of a For Loop, we can expand it as follows:

keyRing = {"Key1":1, "Key2":2, "Key3":3}
print("Key, Value pairs:")
for key, value in keyRing.items():
    print(str(key) + ":" + str(value))
[Output]
“[Key, Value pairs:”]
“Key1:1”
“Key2:2”
“Key3:3”

You can still utilize traditional 0 based indexing with a dict, by using the enumerate() method:

.enumerate() - Gives index position, and its associated KEY, but not value.

keyRing = {"Key1":1, "Key2":2, "Key3":3}
print("Key, Value pairs:")
for key, value in enumerate(keyRing):
    print(str(key) + ":" + str(value))
[Output]
[Key, Value pairs:]
“0:Key1”
“1:Key2”
“2:Key3”

Now, let’s say you have two lists, but you want to create a fast, mutable dictionary to reference of the contents which hold a referential value to each other, or simply view the references. In this case, you could use the zip() method:

.zip() - Peek at data in k:v pairs, combine using dictionaryName = dict(zip(keys, values))

keys= ['Key1', 'Key2', 'Key3']
doors = [1, 2, 3]
for key, door in zip(keys, doors):
    print(key + ":" + str(door))
[Output]
“Key1:1”
“Key2:2”
“Key3:3”

Creating a dict from lists:

dictionaryName = dict(zip(keys, doors))

Tinkering With Dictionaries

Here is a small project (which I use loosely) I was working on to stay sharp with general dictionary methods of construction and manipulation.

DictionaryFairy

Dictionary Tools and Shortcuts

Class

class dictionaryFairy(object):

Generate Dictionary With Zip

    #Create Dictionary with a Zip and Loop approach
    def createDictLoop(self, keys, values):
        zipper = zip(keys, values)
        outDict = {}
        for k, v in zipper:
            outDict[k] = v
        return outDict

Generate Dictionary with Comprehension


    #Create a Dictionary with a Dictionary Comprehension approach
    def createDictComprehension(self, keys, values):
        zipper = zip(keys, values)
        outDict = {k:v for (k, v) in zipper}
        return outDict

Generate Dictionary with a Dict(Zip())

    #Create a Dictionary directly with a dict(zip()) approach
    def createDictDirect(self, keys, values):
        outDict = dict(zip(keys, values))
        return outDict

Comparing Dictionaries

    #Compare Dictionary sizes, return the larger 
    def compareDicts(self, dict1, dict2):
        d1 = len(dict1)
        d2 = len(dict2)

        # Check if both dictionaries are empty
        if not d1 and not d2:
            print("No contents")
            return None

        # Check if dictionaries are the same size
        if d1 == d2:
            print("No difference")
            return None

        # Return the larger Dictionary with a Max() comparison
        else:
            decider = max(d1, d2)
            if d1 == decider:
                print(dict1)
                return dict1
            else:
                print(dict2)
                return dict2
Written on November 1, 2017