Variables, Lists, and Dictionaries (3/3)
Working with Dictionaries
Lists are extremely useful for storing multiple pieces of data within a specific sequence. However, sometimes you want to be able to recall a piece of data without knowing its exact position in a List. For this you can use Dictionaries, which store multiple pieces of data by tying them to unique keys. You can then use the keys to recall the data. For this reason, Dictionary entries are often called 'key-value pairs'.
To create a Dictionary in Python you use curly braces, separating keys and values with a colon (:
), and multiple entries with comma (,
):
myDictionary = {'a': 1, 'b': 2, 'c': 3}
In this Dictionary, the integers 1, 2, and 3 are tied to their unique keys, 'a', 'b', and 'c'. Note that keys must be strings, while values can be any data type. To retrieve a piece of data from this Dictionary, you can again use the square bracket notation, this time passing in a key instead of an index:
myDictionary = {'a': 1, 'b': 2, 'c': 3}
print(myDictionary['a'])
To add entries to a Dictionary, you just have to specify the data that relates to a particular key using the =
operator and the same square bracket syntax:
myDictionary = {'a': 1, 'b': 2, 'c': 3}
myDictionary['d'] = 4
print(myDictionary['d'])
As with Lists, you can start with an empty Dictionary and build it up over time:
myDictionary = {}
myDictionary['a'] = 1
myDictionary['b'] = 2
print myDictionary
Like Lists, Dictionaries implement many useful methods for working with the data contained inside. One very useful method is .keys()
, which returns a List of all of the dictionary’s keys, which you can then use to iterate over all the entries in the Dictionary:
python
myDictionary = {'a': 1, 'b': 2, 'c': 3}
print(myDictionary.keys())
For other useful methods you can refer to the proper place in the documentation.
Combining Lists and Dictionaries
Values within lists and dictionaries are not restricted to being single pieces of data, and can be Lists and Dictionaries as well. This allows you to build highly sophisticated data structures that can match the needs of any project. You can access items within such a hierarchical structure by chaining together requests with square brackets. Here is an example:
# start by initializing an empty Dictionary
myDictionary = {}
# add two Lists as entries in the Dictionary
myDictionary['numbers'] = [1, 2, 3, 4, 5]
myDictionary['fruits'] = ['apples', 'oranges', 'bananas']
# add new data to both Lists
myDictionary['numbers'].append(6)
myDictionary['fruits'].append({'berries':['strawberries', 'blueberries']})
# use a compound request to pull data from the Dictionary. This should print 'blueberries'
print(myDictionary['fruits'][-1]['berries'][1])
JSON, one of the most implemented and easiest to work with data formats, is actually based on this concept of nested lists and key-value pairs, and has great support within almost every programming language, including Python and JavaScript. We will work with the JSON format later in this sequence, but for now you can check out its documentation here: http://json.org/.