Organizing Data with Dictionaries

Authors
Dr. Nicholas Del Grosso | Dr. Sangeetha Nandakumar | Dr. Ole Bialas | Dr. Atle E. Rimehaug

Section 1: Fundamental Data Collections: Dictionaries, lists, and tuples

As a grad student, you are likely encountering experimental data that needs organized and structured management. In this section, we delve into the practical application of Python data structures such as dictionaries, lists, and tuples.

Python also has operators for collecting related data together. Most of this course will revolve around the pros and cons of different ways of collecting data, but let’s take a look at them:

“tuple” (fixed sequence) “list” (changeable sequence) “str” (sequence of text characters) “set” {mathematical set)
(1, 2, 3) [1, 2, 3] “123” or ‘123’ {1, 2, 3}

Exercises

Example: Make a list of the first three positive even numbers.

[2, 4, 6]
[2, 4, 6]

Exercise: Make a tuple of the first three odd numbers.

Solution
(1, 3, 5)
(1, 3, 5)

Exercise: Make a list containing the names of two countries in Europe.

Solution
["Germany", "Italy"]
['Germany', 'Italy']

Exercise: Make a set of three animals.

Solution
{'Dog', 'Hamster', 'Cat'}
{'Cat', 'Dog', 'Hamster'}

Exercise: Make a tuple of the two possible bool values.

Solution
(True, False)
(True, False)

Section 2: Key-Value Mappings: Dictionaries

This section focuses more on dictionaries, which is a versatile data structure ideal for storing and retrieving data through key-value pairs. This is particularly useful in scenarios where we need to associate specific values with unique identifiers – be it experimental conditions, subject details, or measurement parameters. The code snippet below shows an example of the basic organization of a dictionary:

{"name": "Emma",   "Date": "2022-07-23"}
#--Key----Value-   -Key-------Value----

You swill tart with basic dictionary operations, such as creating, adding, and accessing elements. This hands-on experience familiarizes you with dictionary syntax and operations. The exercises are designed to reflect realistic use cases, such as storing and accessing metadata from experimental recordings.

Code Description
data = {} Makes an empty Dict
data = {‘a’: 3, ‘b’: 5} Makes a Dict with two items: “a” and “b”
data[‘a’] Accesses the value associated with key ‘a’
data[‘c’] = 7 Adds a new key-value pair ‘c’: 7 to the Dict
list(data.keys()) Retrieves a list of all keys in the Dict

The image dict describes how researcher Tom’s recording is formatted:

Exercises

image = {'height': 1920, 'width': 1080, 'format': 'RGB', 'order': 'F'}
image
{'height': 1920, 'width': 1080, 'format': 'RGB', 'order': 'F'}

Example: Write the code to print out the width of the image, by accessing the "width" key:

image['width']
1080

Exercise: What is the height of the image?

Solution
image['height']
1920

Exercise: How are the pixel data in the image formatted?

Solution
image['format']
'RGB'

Exercise: What does the error message say, if you use the same syntax to find out which key has the value 1080 ? What does this tell you about how key-value maps like Dictionaries are designed?

Solution

Exercise: Make a dictionary: Reorganize the code below: tell Python that the three variables below all belong together by putting them into a dictionary called session.

Solution
subject = "Josie"
date = "2023-07-23"
group = "control"

session = {'subject': subject, 'date': date, 'group': group}
session
{'subject': 'Josie', 'date': '2023-07-23', 'group': 'control'}

Exercise: Check that the dictionary is constructed properly by getting the subject from it. It should show “Josie”

Solution
session['subject']
'Josie'
default_session = {'subject': 'Ken', 'experimenter': 'Barbie', 'time': '09:00', 'notes': 'Nothing new.'}
today_vars = {'subject':  'Allan', 'notes': 'Did a good job.'}

Section 3: Analysing Data stored in Dicts

The challenge with analyzing dict data is that dicts are not “sequences”, and neither are dict_keys() or dict_values(), so before putting them into a statistics function we should first turn dict_values() into a list using the list() function. For example:

>>> data = {'x': 1, 'y': 2}

>>> data.values()
dict_values([1, 2])

>>> list(data.values())
[1, 2]

>>> np.mean(list(data.values()))
1.5

Useful Functions for the below Exercises:

Function Example Description
len() len(the_dict) The total number of items
np.mean() np.mean(list(the_dict.values()) The mean of the dict’s values
np.min() np.min(list(the_dict.values())) The minimum of the dict’s values

Let’s get some practice querying dicts and calculating some statistics on dicts using Numpy.

Exercises

import numpy as np

Exercise: Using the following dict, calculate what was the average hours of sleep that our friends got last night:

hours_of_sleep = {'Jason': 5, 'Kimberly': 9, 'Billy': 7, 'Trini': 6, 'Zack': 8}
Solution
np.mean(list(hours_of_sleep.values()))
7.0

Exercise: How many total people in the following dataset were in our sleep study?

hours_of_sleep = {'Jason': 5, 'Kimberly': 9, 'Billy': 7, 'Trini': 6, 'Zack': 8}
Solution
len(hours_of_sleep)
5

Exercise: What was the average amount of sleep on day 2 in the following dataset?

hours_of_sleep = {
    'Day1': [5, 7, 3, 3, 4, 6, 8, 9],
    'Day2': [5, 7, 8, 5, 6, 7, 8, 4],
}
Solution
np.mean(hours_of_sleep['Day2'])
6.25

Use the following dataset to answer the questions below

Tip: you can index multiple times (e.g. data['Monday']['Morning'] or data['Monday'].keys())

hours_of_sleep = {
    'Day1': {'Jason': 5, 'Kimberly': 9, 'Billy': 7, 'Trini': 6, 'Zack': 8},
    'Day2': {'Billy': 10, 'Kimberly': 7, 'Trini': 7, 'Jason': 4},
    'Day3': {'Trini': 8, 'Zack': 6, 'Jason': 9, 'Billy': 9},
}

Example: How many hours of sleep did Trini get on Day 2?

hours_of_sleep['Day2']['Trini']
7

Exercise: How many hours of sleep did Billy get on Day 1?

Solution
hours_of_sleep['Day1']['Billy']
7

Exercise: How much sleep did Zack get on Day 3?

Solution
hours_of_sleep['Day3']['Zack']
6

Exercise: How many people were in the study on Day 1?

Solution
len(hours_of_sleep['Day1'])
5

Exercise: How many people were still in the study on Day 3?

Solution
len(hours_of_sleep['Day3'])
4

Exercise: Was the average amount of sleep higher on day one or day three?

Solution
day1 = np.mean(list(hours_of_sleep['Day1'].values()))
day3 = np.mean(list(hours_of_sleep['Day3'].values()))
day1, day3
(7.0, 8.0)