Computation for Linguists

Dict Review & Nesting

Dr. Andrew M. Byrd

2025-10-29

Review

  • What did you learn last time?

Recap from Last Few Weeks

  1. Data Types
  2. Control Structures
  3. Lists, Dicts, Series, DataFrames

Review Activity

  • Copy the following speech, and split it up into a list making all words lower case.
jfk = "This year’s space budget is three times what it was in January 1961, and it is greater than the space budget of the previous eight years combined. That budget now stands at $5,400,000 a year — a staggering sum, though somewhat less than we pay for cigarettes and cigars every year. Space expenditures will soon rise some more, from 40 cents per person per week to more than 50 cents a week for every man, woman and child in the United States, for we have given this program a high national priority — even though I realize that this is in some measure an act of faith and vision, for we do not now know what benefits await us. But if I were to say, my fellow citizens, that we shall send to the moon, 240,000 miles away from the control station in Houston, a giant rocket more than 300 feet tall, the length of this football field, made of new metal alloys, some of which have not yet been invented, capable of standing heat and stresses several times more than have ever been experienced, fitted together with a precision better than the finest watch, carrying all the equipment needed for propulsion, guidance, control, communications, food and survival, on an untried mission, to an unknown celestial body, and then return it safely to Earth, re-entering the atmosphere at speeds of over 25,000 miles per hour, causing heat about half that of the temperature of the sun — almost as hot as it is here today — and do all this, and do it right, and do it first before this decade is out — then we must be bold. I’m the one who is doing all the work, so we just want you to stay cool for a minute. [laughter] However, I think we’re going to do it, and I think that we must pay what needs to be paid. I don’t think we ought to waste any money, but I think we ought to do the job. And this will be done in the decade of the sixties. It may be done while some of you are still here at school at this college and university. It will be done during the term of office of some of the people who sit here on this platform. But it will be done. And it will be done before the end of this decade. I am delighted that this university is playing a part in putting a man on the moon as part of a great national effort of the United States of America. Many years ago, the great British explorer George Mallory, who was to die on Mount Everest, was asked why did he want to climb it? He said, “Because it is there.” Well, space is there, and we’re going to climb it, and the moon and the planets are there, and new hopes for knowledge and peace are there. And, therefore, as we set sail we ask God’s blessing on the most hazardous and dangerous and greatest adventure on which man has ever embarked. Thank you."
  • Use:
import re

jfk_words = re.split(r"[\s\W]+", jfk)
jfk_words = [word for word in jfk_words if word]

Counting Words in JFK

  • We’ve already counted the number of words in a list:
len(jfk_words)

Counting words in JFK

  • Do you remember how to count how many unique instances of a word there are? (How many ‘the’, ‘as’, etc.)

Counting words in JFK

  1. We created an empty dictionary
  2. We looped through our list
  3. In each turn of the loop, we looked inside the dictionary to see if the current word was there.
  4. If it was, we increased its value by 1.
  5. If it wasn’t, we added it, making its value equal to 1.

Review Activity

  • Following the instructions on the previous slide, try to create a dictionary that counts how many words there are in the JFK speech.

Counting words in JFK

  • To match words with word counts, we created a dict:
    • dict = key : value

Lists to Dictionaries to DataFrames

Lists to Dictionaries

  • In the jfk example, we moved from a string to a 1D list to a 2D dictionary
  • How might we combine two lists to make a dictionary?

Lists to Dictionaries

list1 = ["a", "b", "c", "d"]
list2 = [0, 1, 2, 3]

new_dict = {}

for i in list1:
  for j in list2:
    new_dict[i] = j

print(new_dict)

Lists to Dictionaries: Dict Comprehension

  • zip() takes two or more iterables (like lists) and pairs up their elements by index
list1 = ["a", "b", "c", "d"]
list2 = [0, 1, 2, 3]

new_dict = {i: j for i, j in zip(list1, list2)}

print(new_dict)

to DataFrame

  • Since pd DataFrames need just two Series, dictionaries are easy to convert over.
  • However…
import pandas as pd

df = pd.DataFrame(new_dict)
df

Lists to Dictionaries to DataFrames

  • How do we fix this code?
import pandas as pd

list1 = ["a", "b", "c", "d"]
list2 = [0, 1, 2, 3]

new_dict = {}

for i in list1:
  for j in list2:
    new_dict[i] = j

df = pd.DataFrame(new_dict)
df

Converting multiple lists to dictionaries

  • Remember zip() from a couple minutes ago?

Converting multiple lists to dictionaries

list1 = ["a", "b", "c", "d"]
list2 = [0, 1, 2, 3]
list3 = ["alpha", "beta", "gamma", "delta"]
list4 = ["fee", "fie", "fo", "fum"]


list2dict = {i: [j, k, l] for i, j, k, l in zip(list1, list2, list3, list4)}

list2dict

to DataFrame

import pandas as pd

df2 = pd.DataFrame(list2dict)
df2

Activity:

  1. Copy the below lists:
consonant =  ["p", "b", "t", "d", "k", "g", "s", "z", "m", "n", "l", "r", "w", "j", "h"]
place = ["bilabial", "bilabial", "alveolar", "alveolar", "velar", "velar", "alveolar", "alveolar", "bilabial", "alveolar", "alveolar", "alveolar", "labial-velar", "palatal", "glottal"]
manner = ["stop", "stop", "stop", "stop", "stop", "stop", "fricative", "fricative", "nasal", "nasal", "lateral", "trill", "glide", "glide", "fricative"]
voice = ["voiceless", "voiced", "voiceless", "voiced", "voiceless", "voiced", "voiceless", "voiced", "voiced", "voiced", "voiced", "voiced", "voiced", "voiced", "voiceless"]
  1. Convert these lists into a dictionary, with the “consonant” serving as the key.
  2. Next, convert the dictionary as a pd.DataFrame.
  3. Finally, export the pd.DataFrame using df.to_csv("filename.csv", index=False)

Nested Strings, Lists, and Dicts

Nesting

  • Earlier, we saw that we can embed multiple loops into a script
list1 = ["a", "b", "c", "d"]
list2 = [0, 1, 2, 3]

new_dict = {}

for i in list1:
  for j in list2:
    new_dict[i] = j

print(new_dict)

Nested Strings

  • We can run multiple loops to access subelements of a list:
list = ["eeny", "meeny", "miney", "mo"]

for i in list:
  for c in i:
    print(c)

Nested Strings

  • You could use this for
words = ["eeny", "meeny", "miney", "mo"]
words_dict = {}

for w in words:
    vowels = 0               # temporary variable counter
    for c in w:              
        if c in "aeiou":     # check if the letter is a vowel
            vowels += 1      # increment the counter
    print(w, ":", vowels, "vowels")
    words_dict[w] = vowels
    
print(words_dict)

Nested Lists

sentences = [
    ["the", "cat", "sleeps"],
    ["the", "dog", "runs"],
    ["the", "bird", "flies"]
]

for sentence in sentences:
  for w in sentence:
    print(w)

Nested Lists: Activity

  • Copy the following list(s), and (1) print each syllable on its own line and (2) count the total number of syllables
words = [
    ["lin", "guis", "tics"],
    ["pho", "no", "lo", "gy"],
    ["mor", "pho", "lo", "gy"]
]