Nested data structures

Question Click to View Answer

What does the following code print?

arr = [
    [10, 20],
    [30, 40],
]

print(arr[1][0])

30 is printed.

arr[1] fetches the second sub-array and the first element of that sub-array is fetched.

It might be easier to understand this code snippet.

tmp = arr[1]
print(tmp) # prints [30, 40]
print(tmp[0]) # prints 30

What does the following code print?

people = [
    {"name": "mary", "job": "programmer"},
    {"name": "ted", "job": "plumber"},
]

print(people[0]["job"])

"programmer" is printed.

people is a list of dictionaries.

people[0]["job"] fetches the first dictionary in the list and then returns the string associated with the "job" key.

What does the following code print?

stuff = {
    "drink": {"color": "black"},
    "toy": {"min_age": 4, "max_age": 10},
}


print(stuff["toy"]["max_age"])

10 is printed.

stuff is a nested dictionary data structure.

It might be easier to understand this code snippet.

tmp = stuff["toy"]
print(tmp) # {"min_age": 4, "max_age": 10}
print(tmp["max_age"]) # 10

What does the following code print?

mateo = {
    "wife": "liz",
    "kids": ["mario", "camila", "sara"],
}

print(len(mateo["kids"]))

3 is printed. Mateo has 3 kids!

mateo["kids"] returns a list with three items.

What does the following code print?

arr = [
    ["coke", "b"],
    ["c", "d"],
]

arr[0][0] = "a"

print(arr)

[['a', 'b'], ['c', 'd']] is printed.

arr[0][0] = "a" mutates the array and replaces the "coke" string with "a".

What does the following code print?

superheros = [
    {"name": "logan", "power": "strong"},
    {"name": "cyclops", "power": "good attitude"},
]

superheros[1]["power"] = "eye lasers"

print(superheros[1])

{'name': 'cyclops', 'power': 'eye lasers'} is printed.

The cyclops dictionary is mutated and his power was changed from "good attitude" to "eye lasers".

What does the following code print?

new_york = {
    "times square": {"purpose": "tourism"},
    "bensonhurst": {"food": "italian", "fun activity": "fishing"},
}

new_york["times square"]["location"] = "midtown"

print(new_york["times square"])

{'purpose': 'tourism', 'location': 'midtown'} is printed.

This code adds a key / value pair to the new_york["times square"] dictionary.

What does the following code print?

food = {
    "candy": ["snickers", "m&m"],
    "thai": ["yellow curry", "pad ki mao"],
}

food["vietnamese"] = ["pho", "bhan mi"]

print(food["vietnamese"])

['pho', 'bhan mi'] is printed.

This code adds a key / value pair to the food dictionary. The key is "vietnamese" and the value is a list of food types.