0% found this document useful (0 votes)
3 views14 pages

Python 5a Notes - Updated 1

The document provides a comprehensive guide on using dictionaries in Python, explaining their structure as key/value pairs and how to create, add, and retrieve items. It includes code examples for creating a month dictionary and adding country-capital pairs, along with detailed elaborations on each step. Additionally, it outlines a classwork assignment involving the creation of a fruit price dictionary.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Python 5a Notes - Updated 1

The document provides a comprehensive guide on using dictionaries in Python, explaining their structure as key/value pairs and how to create, add, and retrieve items. It includes code examples for creating a month dictionary and adding country-capital pairs, along with detailed elaborations on each step. Additionally, it outlines a classwork assignment involving the creation of a fruit price dictionary.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

P.

1 of 14

Contents

Dictionary in Python ...................................................................................................... 2


Create Dictionary ................................................................................................... 3
Elaboration of pythonDictionary.py ............................................................... 5
Add and retrieve item from Dictionary .................................................................. 8
Elaboration of addToDictionary.py............................................................... 10
Classwork 1 .......................................................................................................... 14
P. 2 of 14

Dictionary in Python
A dictionary is a container object that stores a collection of key/value pairs. It is a
collection that stores the values along with the keys. The keys are like an index
operator. In a list, the indexes are integers. But in dictionary, the key must be a
hashable object. A dictionary cannot contain duplicate keys. Each key maps to one
value. A key and its corresponding value form an item stored in a dictionary. The data
structure is called as dictionary because it resembles a word dictionary, where the
words are the keys and the words’ definitions are the values. A dictionary is also
known as a map hich maps each key to a value.

See the following figure as reference:


P. 3 of 14

Create Dictionary
In Python, we can create a Dictionary by placing sequence of elements within curly {}
braces and separated by ‘comma’. A Dictionary holds a pair of values, one being the
Key and the other being the corresponding value. Notice that values in a dictionary
can be of any datatype and duplication is allowed. Keys, however, can’t be repeated
and must be immutable.

Let’s see the following example (pythonDictionary.py) for your reference:

# Create a dictionary here


monthDict = {1:"January", 2:"Feb", 3:"March", 4:"April", 5:"May", 6:"June",
7:"July", 8:"August", 9:"September", 10:"October", 11:"November",
12:"December"}

# Print out the dictionary


print(monthDict)

print("\n-----------------------------\n")

currentMonth = int(input("What is the current month number? "))

# Use the get() to access a value for a specified key


stringMonth = monthDict.get(currentMonth)

# Print out the value being found from the dictionary


print("\nThe current month is %s !" %stringMonth)

ch = input("")
P. 4 of 14

This is the output of the program:


P. 5 of 14

Elaboration of pythonDictionary.py
1. Dictionary Creation
monthDict = {1:"January", 2:"Feb", 3:"March", 4:"April",
5:"May", 6:"June", 7:"July", 8:"August", 9:"September",
10:"October", 11:"November", 12:"December"}

➢ A dictionary named monthDict is created.


➢ It contains key-value pairs, where:
✓ Keys are integers representing the month numbers (e.g., 1 for January,
2 for February, etc.).
✓Values are strings representing the corresponding month names (e.g.,
"January", "February", etc.).
➢ The dictionary is a simple mapping of month numbers to their names.

2. Printing the Dictionary


print(monthDict)

➢ This prints the entire dictionary to the console.


➢ The output will look like:

{1: 'January', 2: 'Feb', 3: 'March', 4: 'April', 5: 'May',


6: 'June', 7: 'July', 8: 'August', 9: 'September', 10:
'October', 11: 'November', 12: 'December'}

3. Separator
print("\n-----------------------------\n")

➢ A line of dashes (-----------------------------) is printed to visually separate


sections of the output. The \n at the beginning and end creates blank lines
before and after the separator.
P. 6 of 14

4. User Input for the Current Month


currentMonth = int(input("What is the current month number?
"))

➢ The program prompts the user with the message: "What is the current
month number? ".
➢ The user is expected to input an integer representing the current month (e.g.,
1 for January, 2 for February, etc.).
➢ The input() function takes the user input as a string, and the int()
function converts it into an integer.

Example:
➢ If the user inputs 3, the value of currentMonth will be 3.

5. Retrieve the Month Name


stringMonth = monthDict.get(currentMonth)

➢ The .get() method is used to retrieve the value (month name) associated
with the key currentMonth from the monthDict dictionary.
➢ If the key exists in the dictionary, the corresponding month name is stored in
the variable stringMonth.
➢ If the key does not exist, .get() will return None.

Example:
➢ If currentMonth = 3, the method retrieves "March" because it is the value
associated with the key 3.
P. 7 of 14

6. Print the Retrieved Month Name


print("\nThe current month is %s !" %stringMonth)

➢ This prints a formatted string to display the retrieved month name.


➢ The %s is a placeholder for a string, and it is replaced with the value of
stringMonth.

Example Output:
➢ If currentMonth = 3, the output will be:

The current month is March !


P. 8 of 14

Add and retrieve item from Dictionary


To add element in Dictionary, it can be achieved by adding one value at a time. That
means element can be added to a Dictionary by defining value along with the key.
For instance, Dict[Key] = ‘Value’.

You are advised to take a look in the following example (addToDictionary.py) for
further illustration:

# Create an empty dictionary


myDict = {}

# Add element to dictionary one key-value pair at a time


myDict["England"] = "London"
myDict["France"] = "Paris"
myDict["Japan"] = "Tokyo"
myDict["Korea"] = "Seoul"

print(myDict)

print("\n-----------------------------------------\n")

# Print out the dictionary - method 1

# Transform the keys of a dictionary to a list


listKey = list(myDict.keys())

# Transform the keys of a dictionary to a list


listValue = list(myDict.values())

for i in range(len(listKey)): #range(4) i=0,1,2,3


print("The captial of %s is %s." %(listKey[i], listValue[i]))

print("\n-----------------------------------------\n")
P. 9 of 14

# Print out the dictionary - method 2

print("Print out in descending order of country names:\n")

for k,v in sorted(myDict.items(), reverse = True):


print("The captial of %s is %s." %(k, v))

ch = input("")

After running the program, you should get the output like this:
P. 10 of 14

Elaboration of addToDictionary.py
1. Creating an Empty Dictionary
myDict = {}

➢ An empty dictionary named myDict is created.


➢ A dictionary is a data structure that stores key-value pairs.

2. Adding Key-Value Pairs


myDict["England"] = "London"
myDict["France"] = "Paris"
myDict["Japan"] = "Tokyo"
myDict["Korea"] = "Seoul"

➢ Key-value pairs are added to myDict one at a time:


✓ "England" (key) is associated with "London" (value).
✓ "France" (key) is associated with "Paris" (value).
✓ "Japan" (key) is associated with "Tokyo" (value).
✓ "Korea" (key) is associated with "Seoul" (value).

Resulting myDict:
{
"England": "London",
"France": "Paris",
"Japan": "Tokyo",
"Korea": "Seoul"
}
P. 11 of 14

3. Printing the Dictionary


print(myDict)

➢ The entire dictionary is printed to the console.


➢ The output will look like:

{'England': 'London', 'France': 'Paris', 'Japan': 'Tokyo',


'Korea': 'Seoul'}

4. Separator
print("\n-----------------------------------------\n")

➢ Prints a separator line (-----------------------------------------) to visually separate


sections of the output. The \n adds blank lines before and after the
separator.

5. Printing the Dictionary (Method 1)


Transforming Keys and Values into Lists
listKey = list(myDict.keys())
listValue = list(myDict.values())

➢ myDict.keys(): Returns a view object containing all the keys of the


dictionary (e.g., ["England", "France", "Japan", "Korea"]).
➢ myDict.values(): Returns a view object containing all the values of the
dictionary (e.g., ["London", "Paris", "Tokyo", "Seoul"]).
➢ list(): Converts these view objects into lists.

After transformation:
listKey = ["England", "France", "Japan", "Korea"]
listValue = ["London", "Paris", "Tokyo", "Seoul"]
P. 12 of 14

Iterating Over the Lists


for i in range(len(listKey)): # range(4) i = 0, 1, 2, 3
print("The capital of %s is %s." % (listKey[i],
listValue[i]))

➢ len(listKey): Returns the number of keys (4 in this case).


➢ range(len(listKey)): Creates a sequence of numbers from 0 to
len(listKey) - 1 (i.e., 0, 1, 2, 3).

The loop iterates over the indices of the listKey and listValue lists:
➢ For each index i, it prints:
The capital of <listKey[i]> is <listValue[i]>.

Example Output:
The capital of England is London.
The capital of France is Paris.
The capital of Japan is Tokyo.
The capital of Korea is Seoul.

6. Separator
print("\n-----------------------------------------\n")

➢ Another separator is printed for clarity.


P. 13 of 14

7. Printing the Dictionary (Method 2)


Sorting and Iterating
print("Print out in descending order of country names:\n")

for k, v in sorted(myDict.items(), reverse=True):


print("The capital of %s is %s." % (k, v))

➢ myDict.items(): Returns a view object containing all key-value pairs as


tuples (e.g., [("England", "London"), ("France", "Paris"),
("Japan", "Tokyo"), ("Korea", "Seoul")]).
➢ sorted(myDict.items(), reverse=True):
✓ Sorts the key-value pairs by key (alphabetically) in descending order,
because reverse=True.
✓ The sorted result will be:

[("Korea", "Seoul"), ("Japan", "Tokyo"), ("France", "Paris"), ("England", "London")]

➢ The for loop iterates over the sorted key-value pairs, unpacking each pair into
k (key) and v (value).

For each pair, it prints:


The capital of <k> is <v>.

Example Output:
The capital of Korea is Seoul.
The capital of Japan is Tokyo.
The capital of France is Paris.
The capital of England is London.
P. 14 of 14

Classwork 1
Open file fruitDictionary - practice.py. You will see a list named fruitList with several
fruit names as items.

Try to complete the remaining code that the following requirements are fulfilled:
1. Create an empty dictionary called fruitDict
2. Use for-loop to ask user input the price of each fruit

3. Populate the fruitDict dictionary with fruitname as key and price as value
4. Print out the price list as shown in the figure below

You might also like