Python Course 10: Dictionaries

Sample Code

# Create a dictionary
graphics = {"pixel": "Picture Element", "resolution": "Number of pixels on screen", "bitmap":"Image composed of pixels"}

# Print a value
print(graphics["pixel"])

# Loop through the keys
for key in graphics:
    print(key)

# Loop through keys and values (note the .items()!)
for key, value in graphics.items():
    print(key, " is ", value)

# Add an entry to the dictionary
graphics["colour depth"] = "Number of bits used to represent each pixel"

# Check to see entry
print(graphics)

Exercise

  1. Create a python file called dict.py
  2. Create a dictionary called sound containing the following terms: analogue – continuously variable data, digital – data stored as bits, sample – measure of amplitude at a point in time
  3. Print out the value of sample
  4. Add the following two definitions to the dictionary: sampling rate – number of samples taken in a second, Sample resolution – number of bits per sample.
  5. Loop through all the keys in the dictionary and print them out.

Extension

Choose a different subject. Create a key terms dictionary with at least 5 items for that subject. Print out all the keys and values

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s