CS 111 Lecture: JSON & CSV Formats and Real-World Data

1. JSON Format for Sharing Nested Data

1.1 Motivation: Sharing Nested Dictionaries and Lists

When processing real-world data it is incredibly common to have nested structures with lists and dictionaries. For example, here is a dictionary with some of the books of two authors:

In [1]:
authorsDict = {
    "Jane Austen": [
        {"book": "Persuasion", "year": 1818},
        {"book": "Emma", "year": 1815},
        {"book": "Pride and Prejudice", "year": 1813},
        {"book": "Sense and Sensibility", "year": 1811},
        {"book": "Northanger Abbey", "year": 1818},
        {"book": "Mansfield Park", "year": 1814}
     ],
    "Virginia Woolf": [
        {"book": "The Voyage Out", "year": 1915},
        {"book": "Mrs Dalloway", "year": 1925},
        {"book": "Orlando", "year": 1928},
        {"book": "Night and Day", "year": 1919},
        {"book": "To the Lighthouse", "year": 1927},
        {"book": "The Waves", "year": 1931}
    ]
}

And here is a dictionary that specifies the detailed structure of a tweet:

In [2]:
tweet = {
    "id": 1079460557160247297, 
    "source": "Twitter for Android", 
    "text": "Looking fwd to 2019 working w @mediaaction to advance racial justice & #mediajustice in a digital age! This looks like #NoDigitalPrisons, hold FB accountable & ensure POC/ low-income communities can access basic necessities like phone & web. Donate today! https://t.co/9iU1jRSLmt https://t.co/d2kb2Y9EHI", 
    "public_metrics": {
        "retweet_count": 3, 
        "reply_count": 0, 
        "like_count": 5, 
        "quote_count": 0
    }, 
    "entities": {
        "urls": [
            {"start": 268, 
             "end": 291, 
             "url": "https://t.co/9iU1jRSLmt", 
             "expanded_url": "https://www.classy.org/fundraiser/1809542", 
             "display_url": "classy.org/fundraiser/180\u2026", 
             "status": 200, 
             "unwound_url": "https://support.mediajustice.org/fundraiser/1809542"
            }, 
            {"start": 292, 
             "end": 315, 
             "url": "https://t.co/d2kb2Y9EHI", 
             "expanded_url": "https://twitter.com/mediajustice/status/1079436958667919361", 
             "display_url": 
             "twitter.com/mediajustice/s\u2026"}
        ], 
        "mentions": [
            {"start": 30, 
             "end": 42, 
             "username": "mediaaction", 
             "id": "14881478"
            }
        ], 
        "hashtags": [
            {"start": 75, 
             "end": 88, 
             "tag": "mediajustice"
            }, 
            {"start": 123, 
             "end": 140, 
             "tag": "NoDigitalPrisons"}
        ]
    }, 
    "author_id": 80507653, 
    "created_at": "2018-12-30 19:33:46+00:00"
}

We'd like to be able to share data like this with others through files. How to do this?

For the authorsDict, we could imagine converting the dictionary into a file with lines like the following:

Jane Austen: Sense and Sensibility, 1811
Jane Austen: Pride and Prejudice, 1813
Jane Austen: Mansfield Park, 1814
Jane Austen: Emma, 1815
Jane Austen: Persuasion, 1818
Jane Austen: Northanger Abbey, 1818
Virginia Woolf: The Voyage Out, 1915
Virginia Woolf: Night and Day, 1919
Virginia Woolf: Mrs Dalloway, 1925
Virginia Woolf: To the Lighthouse, 1927
Virginia Woolf: Orlando, 1928
Virginia Woolf: The Waves, 1931

But then the user of this file would have to do a lot of work to convert the lines back to a dictionary.

And what kind of line-based format would we use to represent a much more complicated dictionary like tweet?

1.2 JSON Format Solves the Sharing Problem for Nested Data

JSON format is based on a deceptively simple but brilliant idea: What if we just copied the text of the Python notation for nested dictionaries and lists into a text file, and then developed a library of functions that could:

  • reconstruct the Python data structures by reading files using this notation; and

  • writing Python data structures into files that use this notation

For example, the cat command below shows the contents of the file authors.json, whose contents should look very familiar.

In [3]:
cat authorsDict.json
{
  "Jane Austen": [
    {"book": "Persuasion", "year": 1818},
    {"book": "Emma", "year": 1815},
    {"book": "Pride and Prejudice", "year": 1813},
    {"book": "Sense and Sensibility", "year": 1811},
    {"book": "Northanger Abbey", "year": 1818},
    {"book": "Mansfield Park", "year": 1814}
  ],
  "Virginia Woolf": [
    {"book": "The Voyage Out", "year": 1915},
    {"book": "Mrs Dalloway", "year": 1925},
    {"book": "Orlando", "year": 1928},
    {"book": "Night and Day", "year": 1919},
    {"book": "To the Lighthouse", "year": 1927},
    {"book": "The Waves", "year": 1931}
  ]
}

Files in this format are called JSON files (for JavaScript Object notation) because it comes from JavaScript's notation for objects and arrays, which are almost identical to Python's notations for dictionaries and lists.

1.3 json.load

The json library contains a load function that parses a JSON file object into a Python object

json.load(fileObj) # read the content of a file into a Python object

For example, here's how to read the contents of the authors.json file into a Python dictionary named loadedDict:

In [4]:
import json

with open('authorsDict.json', 'r') as inFile:
    loadedDict = json.load(inFile)
    
loadedDict
Out[4]:
{'Jane Austen': [{'book': 'Persuasion', 'year': 1818},
  {'book': 'Emma', 'year': 1815},
  {'book': 'Pride and Prejudice', 'year': 1813},
  {'book': 'Sense and Sensibility', 'year': 1811},
  {'book': 'Northanger Abbey', 'year': 1818},
  {'book': 'Mansfield Park', 'year': 1814}],
 'Virginia Woolf': [{'book': 'The Voyage Out', 'year': 1915},
  {'book': 'Mrs Dalloway', 'year': 1925},
  {'book': 'Orlando', 'year': 1928},
  {'book': 'Night and Day', 'year': 1919},
  {'book': 'To the Lighthouse', 'year': 1927},
  {'book': 'The Waves', 'year': 1931}]}

It's important to emphasize that what has been loaded into Python is not a string but an actual dictionary object that has nested lists and dictionaries:

In [5]:
type(loadedDict)
Out[5]:
dict
In [6]:
list(loadedDict.keys())
Out[6]:
['Jane Austen', 'Virginia Woolf']
In [7]:
loadedDict['Jane Austen']
Out[7]:
[{'book': 'Persuasion', 'year': 1818},
 {'book': 'Emma', 'year': 1815},
 {'book': 'Pride and Prejudice', 'year': 1813},
 {'book': 'Sense and Sensibility', 'year': 1811},
 {'book': 'Northanger Abbey', 'year': 1818},
 {'book': 'Mansfield Park', 'year': 1814}]
In [8]:
loadedDict['Jane Austen'][2]
Out[8]:
{'book': 'Pride and Prejudice', 'year': 1813}
In [9]:
loadedDict['Jane Austen'][2]['book']
Out[9]:
'Pride and Prejudice'

Indeed, the dictionary loadedDict is structurally equal to authorsDict!

In [10]:
loadedDict == authorsDict
Out[10]:
True

1.4 json.dump

Rather than manually copy Python data structures into text files, we can use the json.dump function to automatically write the characters of the Python notation into a given file.

json.dump(someData, fileObj) # write the Python notation for someData into a file

For example here's how to automatically write the authorsDict dictioary into a file named authorsDict2:

In [11]:
with open('authorsDict2.json', 'w') as outFile:
    json.dump(authorsDict, outFile)

By default, json.dump eliminates much of the whitespace that makes authorsDict more readable for humans:

In [12]:
cat authorsDict2.json
{"Jane Austen": [{"book": "Persuasion", "year": 1818}, {"book": "Emma", "year": 1815}, {"book": "Pride and Prejudice", "year": 1813}, {"book": "Sense and Sensibility", "year": 1811}, {"book": "Northanger Abbey", "year": 1818}, {"book": "Mansfield Park", "year": 1814}], "Virginia Woolf": [{"book": "The Voyage Out", "year": 1915}, {"book": "Mrs Dalloway", "year": 1925}, {"book": "Orlando", "year": 1928}, {"book": "Night and Day", "year": 1919}, {"book": "To the Lighthouse", "year": 1927}, {"book": "The Waves", "year": 1931}]}

But this lack of whitepace does not at all affect json.load which can read authorsDict2.json just fine:

In [13]:
with open('authorsDict2.json', 'r') as inFile2:
    loadedDict2 = json.load(inFile2)
    
loadedDict2
Out[13]:
{'Jane Austen': [{'book': 'Persuasion', 'year': 1818},
  {'book': 'Emma', 'year': 1815},
  {'book': 'Pride and Prejudice', 'year': 1813},
  {'book': 'Sense and Sensibility', 'year': 1811},
  {'book': 'Northanger Abbey', 'year': 1818},
  {'book': 'Mansfield Park', 'year': 1814}],
 'Virginia Woolf': [{'book': 'The Voyage Out', 'year': 1915},
  {'book': 'Mrs Dalloway', 'year': 1925},
  {'book': 'Orlando', 'year': 1928},
  {'book': 'Night and Day', 'year': 1919},
  {'book': 'To the Lighthouse', 'year': 1927},
  {'book': 'The Waves', 'year': 1931}]}
In [14]:
loadedDict2 == authorsDict
Out[14]:
True

It is not possible for json.dump to preserve the exact whitespace a programmer has used to format their data in Python, but json.dump does have some optional keyword arguments that can make the JSON file easier to read. For example:

In [15]:
with open('authorsDict3.json', 'w') as outFile:
    json.dump(loadedDict, outFile,
              indent=2,
              sort_keys=True, 
              )
In [16]:
cat authorsDict3.json
{
  "Jane Austen": [
    {
      "book": "Persuasion",
      "year": 1818
    },
    {
      "book": "Emma",
      "year": 1815
    },
    {
      "book": "Pride and Prejudice",
      "year": 1813
    },
    {
      "book": "Sense and Sensibility",
      "year": 1811
    },
    {
      "book": "Northanger Abbey",
      "year": 1818
    },
    {
      "book": "Mansfield Park",
      "year": 1814
    }
  ],
  "Virginia Woolf": [
    {
      "book": "The Voyage Out",
      "year": 1915
    },
    {
      "book": "Mrs Dalloway",
      "year": 1925
    },
    {
      "book": "Orlando",
      "year": 1928
    },
    {
      "book": "Night and Day",
      "year": 1919
    },
    {
      "book": "To the Lighthouse",
      "year": 1927
    },
    {
      "book": "The Waves",
      "year": 1931
    }
  ]
}

1.5 Upsides and Downsides of JSON

Upsides

  • In practice, using JSON works for most Python values with list and dictionaries without any need for special processing to write them to or read them from a file.

  • Although sharing could also be accomplished by just sharing a Python .py file with the data, JSON format can be written and read in any programming language, which makes it a universal standard for representing data with values like lists and dictionaries.

These upsides make JSON the most popular file format for representing complex data.

Downsides

JSON only supports a subset of of the notations used in Python, so values not handled still require special processing:

  • In JSON objects (dictionaries), keys must be strings; no other key type is allowed.

  • JSON does not have tuples. json.dump will convert all tuples to lists.

  • Python values like ranges, dictionary views, functions, etc. cannot be represented in JSON without special-case processing.

Also, some notations are different in JSON and Python:

  • Python's capital True must be written as lowercase true in JSON

  • Python's capital False must be written as lowercase false in JSON

  • Python's None must be written as null in JSON

  • In JSON, strings must be delimited by double quotes. Single-quoted strings and strings with triple single quotes and triple double quotes are not allowed.

  • Python allows trailing comma in lists & dictionaries, but JSON does not.

1.6 Exercise: From text to JSON

You are given the file 'fruitPrices.txt' that contains prices for various fruits. Write the function fruitConversion that will:

  1. Read the content of the file 'fruitPrices.txt' and store it as a dictionary, making sure the prices are converted into floats.
  2. Save the dictionary into the JSON file 'fruitPrices.json'.

fruitPrices.txt

apples: 2.99
oranges: 3.29
bananas: 1.49
grapes: 5.99
kiwis: 2.59

fruitPrices.json

{"apples": 2.99, "oranges": 3.29, "bananas": 1.49, "grapes": 5.99, "kiwis": 2.59}
In [17]:
def fruitConversion(filename):
    """Write a function that:
    1. reads the content from filename
    2. splits the lines and inserts the key:value pairs into a dictionary
    3. saves the dictionary into a JSON file (that shares the name with the original file)
    """
    # Your code here
    with open(filename, 'r') as inputData:
        fruitsDct = {}
        for line in inputData:
            fruit, price = line.split(':')
            fruitsDct[fruit] = float(price)
     
    newFileName = filename.split('.')[0] + '.json'
    with open(newFileName, 'w') as outFile:
        json.dump(fruitsDct, outFile)
In [18]:
# Test the function
fruitConversion('fruitPrices.txt')

Let's view the file:

In [19]:
cat fruitPrices.json
{"apples": 2.99, "oranges": 3.29, "bananas": 1.49, "grapes": 5.99, "kiwis": 2.59}

If you were successful, you should be able to see the dictionary in the JSON file.

1.7 Additional Examples of JSON

You might be surprised to learn that the .ipynb files you've been using all semeter are actually just JSON files! For example, here is the contents of the .ipynb file for this lecture:

In [20]:
cat lec18_json_csv_real-world-data.ipynb

For a challenge problem involving the JSON representation of tweets, see below this Challenge Problem: Work with real-world JSON files

2. Working with CSV files

A CSV (comma-separated values) file is a file within which the values are separated by commas. An appropriate application like Excel can display this data as a table of rows and columns. However, a CSV file is a text file, thus, we can read its content similarly to all text files we have seen so far, with the simple twist that we need to split values at commas. Below is a function that does that:

In [21]:
def tuplesFromFile(filename):
    '''Read each line from opened file, 
    strip white space, 
    split at commas, 
    convert as tuple and 
    return a list of tuples.
    ''' 
    with open(filename, 'r') as inputFile:                
        theTuples = [tuple(line.strip().split(','))       # using list comprehension
                              for line in inputFile]      # implicitely uses .readline()
    return theTuples

Let's read the content of the file us-states.csv:

In [22]:
statesData = tuplesFromFile("us-states.csv")
len(statesData)
Out[22]:
51

There are 51 entries, because the first one is the tuple with the column names:

In [23]:
statesData[:4]
Out[23]:
[('State', 'StatePop', 'Abbrev.', 'Capital', 'CapitalPop'),
 ('Alabama', '4921532', 'AL', 'Montgomery', '198525'),
 ('Alaska', '731158', 'AK', 'Juneau', '32113'),
 ('Arizona', '7421401', 'AZ', 'Phoenix', '1680992')]

There are so many things we can do with this data, but for the moment, we will try something simple: create a CSV file that will look like this:

Let's first create the data that looks similar to what the file should contains:

In [24]:
capitals = [] # new list to store tuples of ("Capital, Abbr", Population)

for _,_,abbr,cap,capPop in statesData[1:]:         # notice the tuple assignment, since each line is a tuple
                                                   # also, we're skipping the row at index 0 
    capitals.append((f"{cap}, {abbr}", capPop))    # use the f-string to join two values into a string
    
capitals[:4] # show the first four items
Out[24]:
[('Montgomery, AL', '198525'),
 ('Juneau, AK', '32113'),
 ('Phoenix, AZ', '1680992'),
 ('Little Rock, AR', '197312')]

This worked well. Now we can store this data into a CSV file, making sure that we use comma to separate the values, as well as the newline character, '\n'.

In [25]:
with open("capitals-only.csv", "w") as outF:
    for item in capitals:
        line = f"{item[0]},{item[1]}\n"     # create the line to write in the file
        outF.write(line)

We can verify the the file was created:

In [26]:
cat capitals-only.csv
Montgomery, AL,198525
Juneau, AK,32113
Phoenix, AZ,1680992
Little Rock, AR,197312
Sacramento, CA,513624
Denver, CO,727211
Hartford, CT,122105
Dover, DE,38079
Tallahassee, FL,194500
Atlanta, GA,506811
Honolulu, HI,345064
Boise, ID,228959
Springfield, IL,114230
Indianapolis, IN,876384
Des Moines, IA,214237
Topeka, KS,125310
Frankfort, KY,27679
Baton Rouge, LA,220236
Augusta, ME,18681
Annapolis, MD,39174
Boston, MA,692600
Lansing, MI,118210
St. Paul, MN,308096
Jackson, MS,160628
Jefferson City, MO,42838
Helena, MT,32315
Lincoln, NE,289102
Carson City, NV,55916
Concord, NH,43627
Trenton, NJ,83203
Santa Fe, NM,84683
Albany, NY,96460
Raleigh, NC,474069
Bismarck, ND,73529
Columbus, OH,898553
Oklahoma City, OK,655057
Salem, OR,174365
Harrisburg, PA,49528
Providence, RI,179883
Columbia, SC,131674
Pierre, SD,13646
Nashville, TN,670820
Austin, TX,978908
Salt Lake City, UT,200567
Montpelier, VT,7855
Richmond, VA,230436
Olympia, WA,46478
Charleston, WV,46536
Madison, WI,259680
Cheyenne, WY,64235

The data is stored in this new file. Will our function tuplesFromFile be able to correctly read this file?

In [27]:
capitals2 = tuplesFromFile("capitals-only.csv")
capitals == capitals2
Out[27]:
False

We didn't get back the same content that we put in. That is cause for concern. Let's look at each list separately:

In [28]:
capitals[:3]
Out[28]:
[('Montgomery, AL', '198525'),
 ('Juneau, AK', '32113'),
 ('Phoenix, AZ', '1680992')]
In [29]:
capitals2[:3]
Out[29]:
[('Montgomery', ' AL', '198525'),
 ('Juneau', ' AK', '32113'),
 ('Phoenix', ' AZ', '1680992')]

We can see what happened: our function tuplesFromFile has split the values at the comma, and created a three-element tuple, instead of the two-element tuple we wrote into the file. There are certainly ways to deal with this, but having to write custom-made code everytime we read a new file that we haven't seen before, is not sustainable. This is where Python libraries (or modules) come handy. They contain functions that take into account all possible scenarios, and allow us to abstract away the details of each file.

The json module we have already encountered is such an example, and today we'll look at the csv module.

3. The csv module to work with CSV data

The csv module has special functions (known as constructors) that create objects that know how to perform certain operations. These objects are similar to the file objects we learned about a few weeks ago.

  1. csv.reader --> an object that knows how to read a file object line by line. It returns a list of lists.
  2. csv.writer --> an object that knows how to write lists into a file object.
  3. csv.DictReader --> an object that knows how to read a file object into a list with each element as a dictionary.
  4. csv.DictWriter --> an object that knows how to write into a file object a list of dictionaries.

Note: In CS111, we will only focus on csv.DictReader and csv.DictWriter. Students who are interested to learn about the other operations should contact an instructor.

In [30]:
import csv

3.1 Understanding csv.DictReader

The csv.DictReader allows us to create an object that knows how to read a line from a CSV file and represent that as a dictionary.

To understand how csv.DictReader works, we will use a very simple CSV file, countries.csv:

country,capital
Canada,Ottawa
Mexico,Mexico City
South Korea,Seoul
Ukraine,Kiev

There are two steps to follow:

  1. Create an object of type csv.DictReader that is tied to a file object
  2. Iterate over the new object to force it to do its work of creating dictionaries
In [31]:
with open("countries.csv", "r") as inputFile:
    dctReader = csv.DictReader(inputFile)       # create an object of the csv.DictReader tied to the file object
    rowDcts = [rowDct for rowDct in dctReader]  # read the content of dctReader, forcing it to iterate
    # The above can be written even more simply with the built-in list function:
    # rowDcts = list(dctReader)
In [32]:
rowDcts
Out[32]:
[{'country': 'Canada', 'capital': 'Ottawa'},
 {'country': 'Mexico', 'capital': 'Mexico City'},
 {'country': 'South Korea', 'capital': 'Seoul'},
 {'country': 'Ukraine', 'capital': 'Kiev'}]

We received a list of dictionaries, where every dictionary represents a row of the CSV table. Let's look at the other objects involved in the block of code:

In [33]:
inputFile # shows the value stored by this variable, an object
Out[33]:
<_io.TextIOWrapper name='countries.csv' mode='r' encoding='UTF-8'>
In [34]:
dctReader # shows the value stored by this variable, an object
Out[34]:
<csv.DictReader at 0x106446e00>
In [35]:
type(inputFile) # the type of our object, this is known as "class name"
Out[35]:
_io.TextIOWrapper
In [36]:
type(dctReader) # the type of our object, this is known as "class name"
Out[36]:
csv.DictReader

Thus, we have two different objects here. The first one knows how to open a file for reading, the second one how to read the content of the file line by line and convert each line into a dictionary.

3.2 Exercise 1: Find the total population that lives in US capitals

In the folder, you'll find the file "us-capitals.csv", which looks like this:

"Capital, Abbr",Population
"Montgomery, AL",198525
"Juneau, AK",32113
"Phoenix, AZ",1680992
"Little Rock, AR",197312
"Sacramento, CA",513624

Your task is to write a function that given the name of the file as a parameter, it will return the total population that lives in all these US capitals.

In [37]:
def totalCapitalsPopulation(filename):
    """This fuction should:
    1. read the content of the given CSV file as a list of dictionaries
    2. Use an accumulator variable to calculate the total population while 
    iterating over the csv.DictReader object.
    Note: It is possible to solve this problem in at least two ways, one of which
    uses list comprehension.
    """
    # Your code here
    totalPop = 0 # accumulator variable
    with open(filename, 'r') as fileObj:
        dctReader = csv.DictReader(fileObj)
        for rowDct in dctReader:
            totalPop += int(rowDct['Population'])
    return totalPop

Test the function:

In [38]:
totalCapitalsPopulation("us-capitals.csv") # Expected value: 13584723
Out[38]:
13584723

OPTIONAL: Alternate solution with list comprehension

Python has a useful built-in function, sum, which can be used to get the sum of all numbers in a list. For example:

In [39]:
sum([1,2,3,4,5])
Out[39]:
15

Write below the alternate solution with list comprehension. It needs to use the function sum.

In [40]:
def totalCapitalsPopulationLC(filename):
    """An alternate solution that uses list comprehension.
    It makes use of the function sum.
    """
    # Your code here
    with open(filename, 'r') as fileObj:
        dctReader = csv.DictReader(fileObj)
        totalSum = sum([int(rowDct['Population']) for rowDct in dctReader])
    return totalSum
In [41]:
totalCapitalsPopulationLC("us-capitals.csv") # Expected value: 13584723
Out[41]:
13584723

3.3 Understanding DictWriter

How to write into a CSV file? You already have created comma-separated files in the past. We also saw one example in this notebook:

capitals = [('Montgomery, AL', '198525'),
            ('Juneau, AK', '32113'),
            ...
            ]
with open("capitals-only.csv", "w") as outF:
    for item in capitals:
        row = f"{item[0]},{item[1]}\n"      # create the line to write in the file
        outF.write(row)

But, this created the issue of how to deal with values that contain commas. This is why we will now discuss csv.DictWriter, which resolves this issue and many others.

Let's say we are given a list of dictionaries (csv.DictWriter only works with a list of dictionaries):

oscarMovies = [{'title': 'CODA', 'year': 2022},
               {'title': 'Nomadland', 'year': 2021},
               {'title': 'Parasite', 'year': 2020}]

Below is a code snippet to write this list of dicts as a CSV file. It uses this structure:

  • Opens a new file for writing
  • Creates a csv.DictWriter object tied to the file object
  • Writer the header of the file (containing the column titles
  • It writes all the rows
In [42]:
oscarMovies = [{'title': 'CODA', 'year': 2022},
               {'title': 'Nomadland', 'year': 2021},
               {'title': 'Parasite', 'year': 2020}]

columns = oscarMovies[0].keys() # find the names of the columns

with open('oscarWinners.csv', 'w') as outFile:
    dctWriter = csv.DictWriter(outFile, fieldnames=columns)
    dctWriter.writeheader() # no need for argument, it was provided above
    dctWriter.writerows(oscarMovies)

Let's check the file:

In [43]:
cat oscarWinners.csv

Swapping Columns

csv.DictWriter has a cool feature. It allows us to easily swap the order of columns, through its parameter 'fieldnames'. Concretely:

In [44]:
columns2 = ['year', 'title']

with open('oscarWinners2.csv', 'w') as outFile:
    dctWriter = csv.DictWriter(outFile, fieldnames=columns2) # new variable, columns2
    dctWriter.writeheader() 
    dctWriter.writerows(oscarMovies) # list of dicts stays the same
In [45]:
cat oscarWinners2.csv

We successfully rewrote the structure of our file with very little effort. That is the power of using Python libraries.

3.4 writeheader, writerows, writerow

In the previous example, we used two methods of the csv.DictWriter object:

  • writeheader --> writes the first row of the file, containing the column names
  • writerows --> writes all the rows, using the data from the list of dictionaries

The latter method is very handy when we already have the list of dictionaries. But sometimes we don't. Sometimes we might be creating a dictionary as we go. In this case, we can use writerow instead. Let's see a simple example:

In [46]:
# writing a file with names and alteregos of famous superheroes

with open('superheroes.csv', 'w') as outFile:
    dctW = csv.DictWriter(outFile, 
                          fieldnames=['name', 'alterego'])
    dctW.writerow({'name': 'Superman', 'alterego': 'Clark Kent'})
    dctW.writerow({'name': 'Scarlet Witch', 'alterego': 'Wanda Maximoff'})
    dctW.writerow({'name': 'Wonderwoman', 'alterego': 'Diana Prince'})
In [47]:
cat superheroes.csv

We left out the method writeheader intentionally, for you to see that if we don't explicitely call it, the csv.DictWriter object will not write the names of the columns, even though it has access to them.

IMPORTANT: If you forget to use .writeheader() and then read a CSV file with csv.DictReader, it will use the first row as the list of column names.

In [48]:
with open('superheroes.csv', 'r') as inputFile:
    dctR = csv.DictReader(inputFile)
    rowDcts = [rowDct for rowDct in dctR]
rowDcts
Out[48]:
[{'Superman': 'Scarlet Witch', 'Clark Kent': 'Wanda Maximoff'},
 {'Superman': 'Wonderwoman', 'Clark Kent': 'Diana Prince'}]

As you can see, this is not what we want.
Remember this example, so that you don't forget to add the header for the file.

3.5 Ex. 2: Write names in three columns

You are given an arbitrarely long list of names that are strings composed of a first, middle, and last name. Here is an example:

scientists = ['Maria Gaetana Agnesi',
              'Marie-Anne Pierrette Paulze',
              'Mary Fairfax Somerville'
              'Elizabeth Garrett Anderson',
              ...
             ]

Use csv.DictWriter to write the content of this list as a CSV file with three columns as shown below. Make use of the methods writeheader, and writerow within a for loop.

first,middle,last  
Maria,Gaetana,Agnesi  
Marie-Anne,Pierrette,Paulze  
Mary,Fairfax,Somerville  
Elizabeth,Garrett,Anderson

This is not straightforward, because we are not given a list of dictionaries, as in previous examples. How can we easily create dictionaries? We show some examples below.

The functions dict and zip

We saw in the lecture about dictionaries that Python has a built-in function, dict, which can create a dictionary from a list of lists or a list of tuples. Here is an example:

In [49]:
fruitsDct = dict([('apple', 2.99), ('banana', 1.49), ('orange', 3.29)])
fruitsDct
Out[49]:
{'apple': 2.99, 'banana': 1.49, 'orange': 3.29}

What made this easy was the fact the we already had a list of tuples. What if our data is not already in this form? For example, we can have two separate lists:

In [50]:
fruits = ['apple', 'banana', 'orange']
prices = [2.99, 1.49, 3.29]

How do we create a list of pairs here? We can use list comprehension!

In [51]:
fruitPrices = [(fruits[i], prices[i]) for i in range(len(fruits))]
fruitPrices
Out[51]:
[('apple', 2.99), ('banana', 1.49), ('orange', 3.29)]

Is there an easier way to do this? Yes, the built-in function zip, which does what the word says, zips together two lists (or more), element-wise.

In [52]:
zip(fruits, prices) # creates an object for performing the zipping
Out[52]:
<zip at 0x106430840>
In [53]:
list(zip(fruits, prices)) # forces zip to do the work
Out[53]:
[('apple', 2.99), ('banana', 1.49), ('orange', 3.29)]
In [54]:
dict(zip(fruits, prices)) # create a dict from the zipped lists
Out[54]:
{'apple': 2.99, 'banana': 1.49, 'orange': 3.29}

Now that we know about how dict and zip work, we can solve our problem more easily.

In [55]:
# these are some early women scientists (18th and 19th century)
scientists = ['Maria Gaetana Agnesi',
              'Marie-Anne Pierrette Paulze',
              'Mary Fairfax Somerville',
              'Elizabeth Garrett Anderson'
             ]
In [56]:
def writeNamesInColumns(namesList, filename):
    """For simplicity, assume all names have all three parts.
    We leave it as an optional excersise for students to deal with names that 
    don't have a middle part.
    You must use csv.DictWriter!
    """
    columns = ['first', 'middle', 'last']
    # Your code here
    with open(filename, 'w') as outFile:
        dctW = csv.DictWriter(outFile, fieldnames=columns)
        dctW.writeheader()
        for name in namesList:
            nameparts = name.split() 
            dctRow = dict(zip(columns, nameparts))
            dctW.writerow(dctRow)

Let's test the function:

In [57]:
writeNamesInColumns(scientists, 'scientists.csv')
In [58]:
cat scientists.csv

It created the file that we intended.

4. Can we sort dictionaries?

Does it make sense to sort a dictionary? What happens if we try to do so?

In [59]:
fruitColors = {"banana": "yellow", "kiwi": "green", 
               "grapes": "purple", "apple": "red", 
               "lemon": "yellow", "pomegranate": "red"}

sorted(fruitColors)
Out[59]:
['apple', 'banana', 'grapes', 'kiwi', 'lemon', 'pomegranate']

We didn't get an error, but all that was sorted were the keys of the dictionary.

Try to predict what we will see in the following lines:

In [60]:
sorted(fruitColors.values())
Out[60]:
['green', 'purple', 'red', 'red', 'yellow', 'yellow']
In [61]:
sorted(fruitColors.items())
Out[61]:
[('apple', 'red'),
 ('banana', 'yellow'),
 ('grapes', 'purple'),
 ('kiwi', 'green'),
 ('lemon', 'yellow'),
 ('pomegranate', 'red')]
In [62]:
sorted(fruitColors.keys())
Out[62]:
['apple', 'banana', 'grapes', 'kiwi', 'lemon', 'pomegranate']

In conclusion we can say:

  • we can sort the list of the keys
  • we can sort the list of the values
  • we can sort the list of the items (the (key,value) pairs)

but not the dictionary itself. Meanwhile, we might be able to sort a list of dictionaries, though it's not straightforward.

First, we need to convert our dictionary of fruitColors into a list of dictionaries, all with the same structure:

In [63]:
# Create a list of dictionaries
fruitColorLst = []

for fruit, color in fruitColors.items():
    fruitColorLst.append({'fruit': fruit, 
                          'color': color})
    
fruitColorLst
Out[63]:
[{'fruit': 'banana', 'color': 'yellow'},
 {'fruit': 'kiwi', 'color': 'green'},
 {'fruit': 'grapes', 'color': 'purple'},
 {'fruit': 'apple', 'color': 'red'},
 {'fruit': 'lemon', 'color': 'yellow'},
 {'fruit': 'pomegranate', 'color': 'red'}]

Can we sort this list?

In [64]:
sorted(fruitColorLst)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[64], line 1
----> 1 sorted(fruitColorLst)

TypeError: '<' not supported between instances of 'dict' and 'dict'

It is not working, becuase Python doesn't have rules for comparing dictionaries, the way that there are rules for comparing strings and tuples (as we have learned when we discussed sorting of sequences). That means, we would have to provide the key parameter to tell Python how to compare the items of this list of dictionaries for sorting.

In [65]:
def byFruit(fruitDct):
    """Helper function to be used in sorted."""
    return fruitDct['fruit']

sorted(fruitColorLst, key=byFruit)
Out[65]:
[{'fruit': 'apple', 'color': 'red'},
 {'fruit': 'banana', 'color': 'yellow'},
 {'fruit': 'grapes', 'color': 'purple'},
 {'fruit': 'kiwi', 'color': 'green'},
 {'fruit': 'lemon', 'color': 'yellow'},
 {'fruit': 'pomegranate', 'color': 'red'}]

Your Turn: Do the same, but by sorting by color.

In [66]:
# Sort fruitColorLst by fruit color
# Your code here

def byColor(fruitDct):
    """Helper function to be used in sorted."""
    return fruitDct['color']

sorted(fruitColorLst, key=byColor)
Out[66]:
[{'fruit': 'kiwi', 'color': 'green'},
 {'fruit': 'grapes', 'color': 'purple'},
 {'fruit': 'apple', 'color': 'red'},
 {'fruit': 'pomegranate', 'color': 'red'},
 {'fruit': 'banana', 'color': 'yellow'},
 {'fruit': 'lemon', 'color': 'yellow'}]

Now that we learned how to sort list of dictionaries, we will put this in practice by reading CSVs, sorting them by various columns, and writing them in CSV files.

5. Working with real-world data: Census 2020

In Section 2: Working with CSV files, we used the file us-states.csv, which contained information about each state, such as:

State,StatePop,Abbrev.,Capital,CapitalPop
Alabama,4921532,AL,Montgomery,198525
Alaska,731158,AK,Juneau,32113
Arizona,7421401,AZ,Phoenix,1680992
Arkansas,3030522,AR,Little Rock,197312
California,39368078,CA,Sacramento,513624
Colorado,5807719,CO,Denver,727211

These are real-world data retrieved from the Census website. In the United States, representation in Congress (House of Representatives) is decided from changes in states' population every ten years. Using the skills that you have learned in the past few lectures, you should be able to write Python code to answer questions with Census data:

  • Which are the most populated US states? Rank the data in that order.
  • Which are the least populated US states? Rank the data in that order.
  • Which US state capitals are the most populated? Rank the data in that order.
  • Which US state capitals are the least populated? Rank the data in that order.
  • What percentage of each US state’s population lives in the state capital? Rank the data by that percentage from the largest to the smallest.

You will write code to read the CSV file, sort it in different ways, and then write the results in new CSV files.

5.1 Read the data from the CSV file

We are providing you with the code of reading a CSV file as a list of dictionaries, so that you can focus on sorting.

In [67]:
import csv
In [68]:
# Read content of CSV file as a list of dictionaries

with open("us-states.csv", 'r') as inputF:
    dctReader = csv.DictReader(inputF)
    stateDctList = [rowDct for rowDct in dctReader]
    
len(stateDctList)
Out[68]:
50

Look up an item of this list:

In [69]:
stateDctList[0]
Out[69]:
{'State': 'Alabama',
 'StatePop': '4921532',
 'Abbrev.': 'AL',
 'Capital': 'Montgomery',
 'CapitalPop': '198525'}

Important: All values in the dictionaries are strings, even the numbers. This is because the CSV format is fundamentally a text format. That means that if we want to use the numerical values, we need to convert them to integer or floats, as appropriate.

5.2 Exercise 3: Rank US States by Population (and write them into a file)

How to approach this problem? Here is the algorithm for it:

  • We will create a helper function byStatePop, which, given a dictionary with state data (one row from our file), returns the appropriate value. We will convert this value into an integer value.
  • We will apply the sorted function to the list of dictionaries of state data (stateDctList), using the key parameter that has as value byStatePop.
  • We will look at the results, in which way are they sorted?
  • We will change the function parameter reverse to change the order of sorting.
  • We will print out the results (to show how we generated results for Slides 15 & 16)
  • You will code a function to write the results into a CSV file
In [70]:
def byStatePop(stateDct):
    """Helper function to be used in sorted."""
    return int(stateDct['StatePop'])
In [71]:
# Sort the list, save it in a variable, check its three first values

sortedStates1 = sorted(stateDctList, key=byStatePop)
sortedStates1[:3]
Out[71]:
[{'State': 'Wyoming',
  'StatePop': '582328',
  'Abbrev.': 'WY',
  'Capital': 'Cheyenne',
  'CapitalPop': '64235'},
 {'State': 'Vermont',
  'StatePop': '623347',
  'Abbrev.': 'VT',
  'Capital': 'Montpelier',
  'CapitalPop': '7855'},
 {'State': 'Alaska',
  'StatePop': '731158',
  'Abbrev.': 'AK',
  'Capital': 'Juneau',
  'CapitalPop': '32113'}]

We can see that it's not in the right order, so we need to use reverse in the sorted function:

In [72]:
sortedStates1 = sorted(stateDctList, key=byStatePop, reverse=True)
sortedStates1[:3]
Out[72]:
[{'State': 'California',
  'StatePop': '39368078',
  'Abbrev.': 'CA',
  'Capital': 'Sacramento',
  'CapitalPop': '513624'},
 {'State': 'Texas',
  'StatePop': '29360759',
  'Abbrev.': 'TX',
  'Capital': 'Austin',
  'CapitalPop': '978908'},
 {'State': 'Florida',
  'StatePop': '21733312',
  'Abbrev.': 'FL',
  'Capital': 'Tallahassee',
  'CapitalPop': '194500'}]

We'll use below an advanced syntax for the f-string, that adds a comma to the integer representation of population values. Do not worry about it, we want you simply to be aware that f-string is very powerful.

In [73]:
# Let's print out the top 6 most populated states (as shown in Slide 15)

print("Top six most populated US states:\n")
for stateDct in sortedStates1[:6]:
    print(f"{stateDct['Abbrev.']} -> {int(stateDct['StatePop']):,}")
Top six most populated US states:

CA -> 39,368,078
TX -> 29,360,759
FL -> 21,733,312
NY -> 19,336,776
PA -> 12,783,254
IL -> 12,587,530

Your Turn:

Now it's your turn. Write the function writeSortedFile, which takes two parameters:

  • a list of sorted dictionaries
  • the name of the file

and writes the content into CSV file. Your function call will look like this:

writeSortedFile(sortedStates1, 
               'statesByPopulation_desc.csv')

The function doesn't return anything. Its side effect is to create the CSV file with the data.

In [74]:
def writeSortedFile(sortedList,  # contains a list of sorted dictionaries
                    filename     # the filename
                   ):
    """Opens a file for writing,
    finds the list of fields (the keys of each dictionary in the list)
    creates a DictWriter object (don't forget the fieldnames)
    writes the header,
    writes the rows.
    """
    # Your code here
    with open(filename, 'w') as outputFile:
        columns = sortedList[0].keys()
        dctW = csv.DictWriter(outputFile, fieldnames=columns)
        dctW.writeheader()
        dctW.writerows(sortedList)

Let's call the function:

In [75]:
writeSortedFile(sortedStates1, 
               'statesByPopulation_desc.csv')

Let's see the created file:

In [76]:
cat statesByPopulation_desc.csv

What if we want to write only two columns and not all of them? We can pass to fieldnames parameter a subset of the columns, but Python will complain about the dictionary to write having more keys. However, there is an additional parameter that will force Python to drop this complain:

dctW = csv.DictWriter(outputFile, 
                      fieldnames=columns,
                      extrasaction='ignore' # ignore keys not in columns
                      )

Optional Task

Modify the function writeSortedFile to only save some of the columns in the CSV file.

In [77]:
def writeSortedFile(sortedList,  # contains a list of sorted dictionaries
                    columns,     # contains a partial list of the columns
                    filename     # the filename
                   ):
    """Opens a file for writing,
    creates a DictWriter object,
    writes the header,
    write the rows
    """
    # Your code here
    with open(filename, 'w') as outputFile:
        dctW = csv.DictWriter(outputFile, 
                              fieldnames=columns,
                              extrasaction='ignore'
                             )
        dctW.writeheader()
        dctW.writerows(sortedList)
In [78]:
writeSortedFile(sortedStates1, 
               ['Abbrev.', 'StatePop'], 
               'statesByPopulation_desc.csv')
In [79]:
cat statesByPopulation_desc.csv

5.3 Exercise 4: Print the least populated US States

This is very similar to the first part of the Section 5.2. Write code that prints out the following six states (the least populated in the US):

Top six least populated US states:

WY -> 582,328
VT -> 623,347
AK -> 731,158
ND -> 765,309
SD -> 892,717
DE -> 986,809
In [80]:
# Your code here

sortedStates2 = sorted(stateDctList, key=byStatePop)

print("Top six least populated US states:\n")
for stateDct in sortedStates2[:6]:
    print(f"{stateDct['Abbrev.']} -> {int(stateDct['StatePop']):,}")
Top six least populated US states:

WY -> 582,328
VT -> 623,347
AK -> 731,158
ND -> 765,309
SD -> 892,717
DE -> 986,809

5.4 Challenge Exercise: sort in both directions

While the notebook makes it easy to solve problems, the solution is scattered in multiple cells. What we would like to have is a series of functions that can be put together to solve a problem once and for all, and then just use the solution with different arguments.

In this task, you will try to write a single function writeSortedColumns, which can be used to solve both questions we encountered above (sort by the most or least populated states, and show a subset of columns). Concretely, the function should take these parameters:

  • it takes the name of a CSV file that needs to be sorted
  • it takes a sorting order (a boolean that is True or False)
  • it takes a list of columns that specify a subset of columns to show

The function should create a new CSV file to contain the sorted columsn. It should use as many helper functions as possible, for example, a function that creates a new file name which combines the existing file name with the words: "ascending" or "descending" (depending on the sorting direction).

In [81]:
# Write the helper function to change the file name
# Your code here

def createFileName(filename, reverseOrder):
    """Helper function to create a new filename.
    """
    name, ext = filename.split('.')
    if reverseOrder == True:
        extra = "descending"
    else:
        extra = "ascending"
    return f"{name}_{extra}.{ext}"
In [82]:
createFileName("us-states.csv", True)
Out[82]:
'us-states_descending.csv'
In [83]:
createFileName("us-states.csv", False)
Out[83]:
'us-states_ascending.csv'
In [84]:
def writeSortedColumns(filename, reverseOrder, columnsList):
    """
    A function that given a CSV filename will:
    - read its content
    - sort it
    - create a new filename based on sorting order
    - write the sorted rows in the new file
    """
    # Your code here
    # Step 1: Read the file
    with open(filename, 'r') as inputFile:
        dctReader = csv.DictReader(inputFile)
        rowsDctList = [rowDct for rowDct in dctReader]
        
    # Step 2: Sort the list of dicts
    sortedRows = sorted(rowsDctList, key=byStatePop, reverse=reverseOrder)
    
    # Step 3: create new file name
    newfilename = createFileName(filename, reverseOrder)
    
    # Step 4: write a new CSV file
    with open(newfilename, 'w') as outputFile:
        dctWriter = csv.DictWriter(outputFile, 
                                   fieldnames=columnsList,
                                   extrasaction='ignore'
                                  )
        dctWriter.writeheader()
        dctWriter.writerows(sortedRows)

Test the function to do the descending order (from the most populous to the least):

In [85]:
writeSortedColumns("us-states.csv", True, ['Abbrev.', 'StatePop'])
In [86]:
cat us-states_descending.csv

Test the function to do the ascending order (from the most populous to the least):

In [87]:
# we are changing the arguments for the 2nd and 3rd parameter
writeSortedColumns("us-states.csv", False, ['State', 'StatePop'])
In [88]:
cat us-states_ascending.csv

Additional Challenge
How would you need to modify the function writeSortedColumns, so that instead of sorting by state population, it sorts by capital population?

6. Challenge Problem: Work with JSON files

You are given a JSON file that contains tweets about the movement Black Lives Matters. These tweets were collected for a research project by a Wellesley research lab.

The JSON file, blmTweets.json contains a list of 1000 tweets as simple dictionaries with two keys, an ID and the text of the tweet:

[{'id': 1072284009122586625, 'text': 'The case of Jacob Walter Anderson from @Baylor is the perfect amalgamation between the #MeToo and #BlackLivesMatter movements. #ThisIsWhyWeAreAngry’}, 
{'id': 1071990529448075264, 'text': 'Now, that you all have some background information to this short story, please go read it at 👉👉👉 https://t.co/KRGkjbNJbY 👈👈👈 #NoJusticeNoPeace #BlackLivesMatter #MissionFree #DefendOurFreedom 😎'},
...
]

Let's load the file to check it out:

In [89]:
import json

with open('blmTweets.json', 'r') as inputFile:
    blmTweets = json.load(inputFile)
    
len(blmTweets)
Out[89]:
1000
In [90]:
blmTweets[0]
Out[90]:
{'id': 1072284009122586625,
 'text': 'The case of Jacob Walter Anderson from @Baylor is the perfect amalgamation between the #MeToo and #BlackLivesMatter movements. #ThisIsWhyWeAreAngry'}

Here are some questions that we can ask of these data:

  1. Which are the most frequently mentioned hashtags?
  2. Do certain hashtags co-occur together more often than others?

To simplify working with data, we will transform our data by storing the lowercased hashtags for each tweet. For example, the two tweets above will become:

[{'id': 1072284009122586625, 'hashtags': ['#metoo', '#blacklivesmatter',
#thisiswhyweareangry’}, 
{'id': 1071990529448075264, 'hashtags': '#nojusticenopeace', '#blacklivesmatter',
'#missionfree', '#defendourfreedom'},
...
]

We will break down the problem to solve it step-by-step.

6.1 Convert a tweet into a list of hashtags

Write a function that given a tweet as a string, returns a list of all (lowercased) hashtags from the tweet. If you want to challenge yourself, try to write the solution with list comprehension (this is optional).

In [91]:
def tweetToHashtags(tweetText):
    """This is the version without list comprehension.
    """
    # Your solution here
    hashtags = []
    words = tweetText.lower().split() # get the list of words
    for word in words:
        if word.startswith('#'):
            hashtags.append(word)
        
    return hashtags
In [92]:
tweetToHashtags(blmTweets[0]['text'])
Out[92]:
['#metoo', '#blacklivesmatter', '#thisiswhyweareangry']

Optional: Write the same function using list comprehension.

In [93]:
def tweetToHashtagsLC(tweetText):
    """This is the version with list comprehension.
    """
    # Your solution here
    return [word for word in tweetText.lower().split() if word.startswith('#')]
In [94]:
tweetToHashtagsLC(blmTweets[0]['text'])
Out[94]:
['#metoo', '#blacklivesmatter', '#thisiswhyweareangry']

6.2 Write a new JSON file with the tweets transformed as hashtag lists

Using the helper function tweetToHashtags, iterate over all the tweets and create a new list of dictionaries {'id': someId, 'hashtags': [some hashtags]} and save in into a JSON file to use to answer our questions.

Note: The JSON file, tweetsWithHashtags.json, can be found in the notebook folder. This way, you can continue with the other subsection, without having to solve this step.

In [95]:
def storeNewTweetFormat(tweetsList, filename):
    """Given a list of tweet dicts, do the following:
    1. Create a new list which will store new dicts, each of them having an 
       id and list of hashtags.
    2. Dump this list into a JSON file, using the provided filename.
    """
    # Your code here
    newTweetList = [] # accumulator variable
    
    for tweet in tweetsList:
        hashtags = tweetToHashtags(tweet['text'])
        newDict = {'id': tweet['id'], 'hashtags': hashtags}
        newTweetList.append(newDict)
        
    with open(filename, 'w') as outputFile:
        json.dump(newTweetList, outputFile)
In [96]:
# Test the code
storeNewTweetFormat(blmTweets, 'tweetsWithHashtags.json')
In [97]:
cat tweetsWithHashtags.json

6.3 Create a frequency dictionary of all hashtags

Using the file 'tweetsWithHashtags.json', you'll write a function that iterates through all the tweet dicts and accumulates a new frequency dictionary that keeps track of all hashtag occurrences.

In [98]:
def findFrequencyHashtags(filename):
    """Given a JSON file that has a list of dicts, each representing a tweet,
    do the following:
    1. Read the list of tweets (load the JSON file)
    2. Iterate over the tweets and keep track of all hashtag occurrences
    into a dictionary.
    3. Return the dictionary.
    """
    # Your code here
    with open(filename) as inputFile:
        tweetsList = json.load(inputFile)
        
    hashtagFreq = {} # accumulator variable
    for tweet in tweetsList:
        hashtags = tweet['hashtags']
        for ht in hashtags:
            hashtagFreq[ht] = hashtagFreq.get(ht, 0) + 1 
            
    return hashtagFreq
In [99]:
hashtagsDct = findFrequencyHashtags('tweetsWithHashtags.json')
len(hashtagsDct)
Out[99]:
1285

Let's explore this dictionary:

In [100]:
list(hashtagsDct.keys())[:5]
Out[100]:
['#metoo',
 '#blacklivesmatter',
 '#thisiswhyweareangry',
 '#interview',
 '#ferguson']
In [101]:
list(hashtagsDct.items())[:5]
Out[101]:
[('#metoo', 31),
 ('#blacklivesmatter', 629),
 ('#thisiswhyweareangry', 1),
 ('#interview', 1),
 ('#ferguson', 22)]

4.4 Save the sorted hashtags into a JSON file

A dictionary, cannot be sorted easily, thus, instead of sorting the dictionary, we can sort the list of its items, that is, the list of tuples (key,value):

[('#metoo', 31),
 ('#blacklivesmatter', 629),
 ('#thisiswhyweareangry', 1),
 ('#interview', 1),
 ('#ferguson', 22)]

In the following, you'll write a function that first sorts the items of the dictionary, then saves the sorted list into a file.

In [102]:
def byFrequency(pair):
    """Helper function for the sorted function.
    Given a tuple such as ('#metoo', 31), it will return number 31.
    """
    return pair[1]
In [103]:
def sortAndSaveFrequentHashtags(hashtagsDict, filename):
    """
    First sort the items of the dictionary in the descending order (largest to lowest),
    then dump the list of tuples into a JSON file named 'filenmae'.
    """
    # Your code here
    sortedPairs = sorted(hashtagsDict.items(), 
                         key=byFrequency, 
                         reverse=True)
    
    with open(filename, 'w') as outputFile:
        json.dump(sortedPairs, outputFile)
In [104]:
# Let's test the function
sortAndSaveFrequentHashtags(hashtagsDct, 'sortedHashtags.json')
In [105]:
cat sortedHashtags.json

This is the end of the notebook!