Wednesday 18 July 2018

Python dictionary examples

Over the course of my ramblings and 3d work I have collated a collection of example scripts that I refer back to every once in a while, perhaps when I forget how to use a particular piece of syntax or if it's something I use fairly irregularly.

Dictionaries are something that I use all-the-time. And if you're looking to get into python scripting then is definitely something you'll want to be using too.

Dictionaries are like a more-lovely list/array.
Here's what I have jotted down in my example_python_dictionary.py file:
# Create an empty dictionary, just like we would with a list.
vegetables = {}

# Append/Create our first entries; 'carrot' and 'tomato'. We assign a sub-dictionary to both of them as their values.
vegetables['carrot'] = {'colour' : 'orange','grown' :' underground'}
vegetables['tomato'] = {'colour' : 'red','grown' : 'vine'}

# An example of looping through each key and values using the in-built '.iteritems()' dictionary method:
for key,value in vegetables.iteritems():
    print key, value

# An example of running logic with a '.get()' method:
for key, value in vegetables.iteritems():
    if value.get("colour") == "orange":
        print "{} is an orange vegie".format(k.title())

# Make it ordered - (Explaination below)
import collections
vegetables = OrderedDict(sorted(vegetables.items()))

One thing about dictionaries, is that by default they store their information un-ordered. This means if we wanted to access the first element when we created the dictionary, it would not necessarily be the first element returned when we go to retrieve the first element later on. 

Think of the process like this:
creating a dictionary = drawing out a new deck of cards
immediately afterwards, python helpfully shuffles this deck of cards, keeping all the cards & data, but not the order. This is to help save memory when dealing with large amounts of data but.. this has caused me more than one headache when I assume that the dictionary would retain the order that it had when I first created it. BEWARE of this.

Happy.. dictionarying?

No comments:

Post a Comment