Tuesday, December 29, 2015

Python how to check if a particular key is in a dictionary

So, making a program based on code from a much more competent programmer, they had gotten as far as capturing our data in a structure called a 'dictionary' which is one of the things that makes python very useful.

My first mistake was in thinking that dictionaries and lists are interechangable. They aren't; lists are single-column and numerically indexed like arrays, dictionaries are a column of tuples, essentially two columns. Lists are declared as list = [], dictionaries are declared as dict = {}. The delight of dictionaries is that they don't have to be iterated through like lists to find a value. You can just ask it for the value at a particular key (first column) and BAM you get back the value (second column). Also, it turns out to be very easy to find if a particular key exists in the entire dictionary. You just say if key in dict: A couple of links showing this:

http://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary
http://stackoverflow.com/questions/19241680/python-check-that-key-is-defined-in-dictionary