PHOT 110: Introduction to programming

LECTURE 10: Data, Dictionaries and Pandas (Ch. 6)

Michaël Barbier, Spring semester (2023-2024)

Structured data: Dictionaries

What is a dictionary ?

A list of key-value pairs with unique keys

# Defining
age = {"joe": 34, "tom": 20, "mary": 50}
print(age)
{'joe': 34, 'tom': 20, 'mary': 50}


# Using dict as a constructor
age = dict([("joe", 34), ("tom", 20), ("mary", 50)])
print(age)
{'joe': 34, 'tom': 20, 'mary': 50}

Operations: indexing, adding, deleting

print(age["mary"])
50


# Adding an element
age["Mikal"] = 56
print(age)
{'joe': 34, 'tom': 20, 'mary': 50, 'Mikal': 56}


# Deleting an element
del age["joe"]
print(age)
{'tom': 20, 'mary': 50, 'Mikal': 56}

Looping over a dictionary key-value pairs

  • methods items(), keys(), and values() extract key-value pairs, keys, and values of the dictionary
  • These can be used within loops:
for k, v in age.items():
  print(k, v)
tom 20
mary 50
Mikal 56

Looping over a dictionary key-value pairs

  • methods items(), keys(), and values() extract key-value pairs, keys, and values of the dictionary
  • These can be used within loops:
for k in age.keys():
  if k != "Mikal":
    print(age[k])
20
50

Looping over a dictionary key-value pairs

  • methods items(), keys(), and values() extract key-value pairs, keys, and values of the dictionary
  • These can be used within loops:
for v in age.values():
  print(v)
20
50
56

Dict comprehension

Similar to list comprehension:

# List comprehension: creating a list
squares = [x**2 for x in range(1, 5)]
print(squares)
[1, 4, 9, 16]


With dictionaries use curly brackets and the colon separator:

# Dict comprehension: creating a Dict / Dictionary
numbers_and_squares = {x: x**2 for x in range(1, 5)}
print(numbers_and_squares)
{1: 1, 2: 4, 3: 9, 4: 16}