Dictionaries#
Question. Find Index of Minimum Value, using for
loops #
Write a function find_min
that accepts as input a list of integers and returns the index of the list item with the minimum value.
def find_min(numbers):
minimum = 1000
i = 0
for element in numbers:
if element < minimum:
minimum = element
min_index = i
i = i + 1
return min_index
assert find_min([9, 5, 1]) == 2, "Test case failed"
print("Test case passed successfully")
Test case passed successfully
Tuple Assignment and for
loops#
Recall, from Lecture 10.3:
x, y = 1, 2
x, y = y, x
print(x, y)
2 1
"""From Lab 12"""
emojis = [('π', "Grinning Face"), ('π', "Beaming Face With Smiling Eyes"),
('π', "Face With Tears of Joy"), ('π€£', "Rolling on the Floor Laughing")]
for icon, desc in emojis:
print(desc)
Grinning Face
Beaming Face With Smiling Eyes
Face With Tears of Joy
Rolling on the Floor Laughing
Built-in enumerate
#
Input =>
list
orset
, atuple
or astr
Output => a List of Tuples:
[(idx0, val0), ... ,( idx_len-1, val_len-1 ) ]
rainbow = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]
print(list(enumerate(rainbow)))
[(0, 'Red'), (1, 'Orange'), (2, 'Yellow'), (3, 'Green'), (4, 'Blue'), (5, 'Indigo'), (6, 'Violet')]
for
loops with enumerate
#
Problem: Given a list sequence
and a value val
, find index of val
in sequence
if present; if not, else return -1
def find_val(sequence, val):
return val_idx
assert find_val([1, 2, 3, 4, 5]) == 0, "Test case 1 failed"
assert find_val(["a", "b", "c", "d"]) == 2, "Test case 2 failed"
assert find_val(["a", "b"], "c") == -1, "Test case 3 failed"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [5], in <cell line: 5>()
1 def find_val(sequence, val):
3 return val_idx
----> 5 assert find_val([1, 2, 3, 4, 5]) == 0, "Test case 1 failed"
6 assert find_val(["a", "b", "c", "d"]) == 2, "Test case 2 failed"
7 assert find_val(["a", "b"], "c") == -1, "Test case 3 failed"
TypeError: find_val() missing 1 required positional argument: 'val'
Question. Find Index of Minimum Value, using for loops AND enumerate#
Write a function find_min
that accepts as input a list of integers and returns the index of the list item with the minimum value.
def find_min(numbers):
minimum = 1000
enum = list(enumerate(numbers))
for idx, num in enum:
if num < minimum:
minimum = num
min_index = idx
return min_index
assert find_min([7, 1, 2]) == 1, "Test case failed"
print("Test case passed successfully")
Lecture 13.1.#
Dictionaries#
Friday, Nov 17#
All of the indexed data structures we have studied so far β strings, lists, and tuplesβ are sequence types, which use contiguous integers, starting from 0, as indices to access the values they contain within them.
Dictionaries#
Dictionaries map Keys to Values
Keys can be any immutable type:
int
,str
,bool
,float
,tuples
Values can be of any type
Dictionaries vs. other Data Structures#
Type |
Collection |
Syntax |
Ordered |
Indexed |
Mutable |
Passed By |
Duplicates Allowed |
---|---|---|---|---|---|---|---|
|
characters |
|
β |
β |
β |
value |
β |
|
any data type |
|
β |
β |
β |
reference |
β |
|
any data type |
|
β |
β |
β |
value |
β |
|
immutable types |
|
β |
β |
β |
value |
β |
|
any data type* |
|
β |
β |
β |
reference |
β** |
* keys can only be immutable type; values can be any data type
** keys can not be duplicate; values can be duplicate
Dictionaries Syntax#
Use curly brackets
{}
to initializeUse square brackets
[]
to:insert keys, and map values to them
access values, using keys
update key-value mappings
The key-value pairs of a dictionary are seperated by commas
,
Each pair contains a key and a value separated by a colon
:
dictionary = {"key1": "value1", "key2": "value2"}
dictionary["value1"]
Creating Dictionaries, and Inserting Key-Value Pairs#
One way to create a dictionary is to start with the empty dictionary and add key-value pairs. The empty dictionary is denoted
{}
:
eng2sp = {} # a dictionary to translate English words into Spanish
eng2sp['one'] = 'uno' # adding a new key "one" and mapping the value "uno" to it
eng2sp['two'] = 'dos' # adding yet another key "one" and mapping the value "dos" to it
print(eng2sp)
Similar to sets, the order of the pairs is unpredictable.
Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output:
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(eng2sp['three'])
Accessing Values#
The values in a dictionary are accessed with Keys, NOT with Indices. Hence,
It doesnβt matter what order in which we write the pairs
There is no need to worry about ordering.
Here is how we use a key to look up the corresponding value:
print(eng2sp['two']) # The key 'two' yields the value 'dos'.
Deleting Key-Value Pairs#
The
del
statement removes a key-value pair from a dictionary.
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(eng2sp)
del eng2sp['two']
print(eng2sp)
Change value associated with an existing key#
Override previous value mapped to the key, using the assignment operator:
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
eng2sp['three'] = 'uno mΓ‘s dos'
print(eng2sp)
Getting length of a Dictionary#
The len
function also works on dictionaries; it returns the number of key-value pairs:
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
len(eng2sp)
Looping over Dictionaries#
You can loop through a dictionary by using a
for
loop.When looping through a dictionary, the target variable of the for loop is set to
keys
of the dictionary
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
for key in eng2sp:
value = eng2sp[1]
print(key)
Dictionary methods#
Dictionaries have a number of useful built-in methods.
As we saw earlier with
strings
andlists
, dictionary methods use dot notation, which specifies the name of the method to the right of the dot and the name of the object on which to apply the method immediately to the left of the dot.
1. dictionary
.keys()
The
keys
method takes a dictionary and returns the list of its keys.
list(eng2sp.keys())
2. dictionary
.values()
The
values
method takes a dictionary and returns the list of its values.
list(eng2sp.values())
3. dictionary
.items()
The
items
method takes a dictionary and returns the list of key-value pairs.
list(eng2sp.items())
Membership operator in
with Dictionaries#
The
in
operator checks if a Key (NOT VALUE) exists in the dictionaryreturns
True
if the key is present in the dictionary andFalse
otherwise
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
'one' in eng2sp
'deux' in eng2sp
This method can be very useful, since looking up a non-existant key in a dictionary causes a runtime error:
eng2esp['dog']
Aliasing and copying#
Because dictionaries are mutable, you need to be aware of aliasing.
Whenever two variables refer to the same object, changes to one affect the other.
If you want to modify a dictionary and keep a copy of the original, use the copy method. For example, opposites is a dictionary that contains pairs of opposites:
opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}
alias = opposites
copy = opposites.copy()
alias['right'] = 'left'
opposites['right']
If we modify copy, opposites is unchanged:
copy['right'] = 'privilege'
opposites['right']
Dictionaries (continued)#
Initializing Dictionaries with Key-Value Pairs
dictionary = {"key1": "value1", "key2": "value2"}
print(dictionary["key1"])
Populating Dictionaries
eng2sp = {} # a dictionary to translate English words into Spanish
eng2sp['one'] = 'uno' # adding a new key "one" and mapping the value "uno" to it
eng2sp['two'] = 'dos' # adding yet another key "one" and mapping the value "dos" to it
print(eng2sp)
Similar to sets, the order of the pairs is unpredictable.
Values in a dictionary are accessed with Keys, with square brackets
[]
print(eng2sp['one']) # The key 'two' yields the value 'dos'.
The
del
statement removes a key-value pair from a dictionary
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print("Before deletion", eng2sp)
del eng2sp['two'] # Deleting key-value pair with key `two`
print("After deletion", eng2sp)
Change value associated with an existing key: Override previous value mapped to the key, using the assignment operator
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print("Before change", eng2sp)
eng2sp['three'] = 'uno mΓ‘s dos'
print("After change", eng2sp)
Getting length of a Dictionary: The
len
function also works on dictionaries; it returns the number of key-value pairs:
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
len(eng2sp)
Looping over Dictionaries: When looping through a dictionary, the target variable of the
for
loop is set tokeys
of the dictionary
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
for random in eng2sp:
value = eng2sp[random]
print(random, value)
dictionary
.keys()
: Thekeys
method returns the list of its keys.
list(eng2sp.keys())
dictionary
.values()
: Thevalues
method returns the list of its values.
print(list(eng2sp.keys()))
print(list(eng2sp.values()))
dictionary
.items()
: Theitems
method returns the list of key-value pairs.
list(eng2sp.items())
Membership operator
in
checks if a Key (NOT VALUE) exists in the dictionaryreturns
True
if the key is present in the dictionary andFalse
otherwise
value in
structure
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
'random' in eng2sp
'deux' in eng2sp
This method can be very useful, since looking up a non-existant key in a dictionary causes a runtime error:
eng2sp['dog']
Questions#
Question 1. Create a Dictionary mapping Morse code to English letters#
def create_morse2eng(morse_code, alphabet):
return morse2eng
morse_code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--",\
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
alphabet = "abcdefghijklmnopqrstuvwxyz"
assert create_morse2eng(morse_code, alphabet) == { '.-' : 'a',\
'-...': 'b',\
'-.-.': 'c',\
'-..' : 'd',\
'.' : 'e',\
'..-.': 'f',\
'--.' : 'g',\
'....': 'h',\
'..' : 'i',\
'.---': 'j',\
'-.-' : 'k',\
'.-..': 'l',\
'--' : 'm',\
'-.' : 'n',\
'---' : 'o',\
'.--.': 'p',\
'--.-': 'q',\
'.-.' : 'r',\
'...' : 's',\
'-' : 't',\
'..-' : 'u',\
'...-': 'v',\
'.--' : 'w',\
'-..-': 'x',\
'-.--': 'y',\
'--..': 'z'}, "Test case failed"
print("All test cases passed successfully")
Question 2. Create a Dictionary mapping English letters to Morse code#
def create_eng2morse(alphabet, morse_code):
return eng2morse
morse_code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--",\
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
alphabet = "abcdefghijklmnopqrstuvwxyz"
assert create_eng2morse(alphabet, morse_code) =={'a': '.-',\
'b': '-...',\
'c': '-.-.',\
'd': '-..',\
'e': '.',\
'f': '..-.',\
'g': '--.',\
'h': '....',\
'i': '..',\
'j': '.---',\
'k': '-.-',\
'l': '.-..',\
'm': '--',\
'n': '-.',\
'o': '---',\
'p': '.--.',\
'q': '--.-',\
'r': '.-.',\
's': '...',\
't': '-',\
'u': '..-',\
'v': '...-',\
'w': '.--',\
'x': '-..-',\
'y': '-.--',\
'z': '--..'}, "Test case failed"
print("All test cases passed successfully")
Question 3. Convert English Text to Morse Code#
def convert_to_morse(txt):
return converted
assert convert_to_morse("what") == ['.--', '....', '.-', '-'], "Test case 1 failed"
assert convert_to_morse("hath") == ['....', '.-', '-', '....'], "Test case 2 failed"
assert convert_to_morse("god") == ['--.', '---', '-..'], "Test case 3 failed"
assert convert_to_morse("wrought") == ['.--', '.-.', '---', '..-', '--.', '....', '-'], "Test case 4 failed"
print("All test cases passed successfully")
Question 4. Sum currency notes#
Given amount
, compute minimum number of bills needed to give back the change.
Assume you have infinite banknotes for each denomination.
U.S. currency denominations (implicit)
def sum_change(change_notes):
return summ
assert sum_change({100: 3, 50: 1, 20: 2, 10: 0, 5: 1, 1: 1}) == 396, "Test case 1 failed"
assert sum_change({100: 0, 50: 0, 20: 0, 10: 1, 5: 1, 1: 3}) == 18, "Test case 2 failed"
assert sum_change({100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 1: 0}) == 0, "Test case 3 failed"
assert sum_change({100: 0, 50: 0, 20: 1, 10: 1, 5: 1, 1: 4}) == 39, "Test case 4 failed"
assert sum_change({100: 1, 50: 1, 20: 2, 10: 0, 5: 1, 1: 4}) == 199, "Test case 5 failed"
print("All test cases passed successfully")
Question 5. Change-making problem#
Given amount
, compute minimum number of bills needed to give back the change.
Assume you have infinite banknotes for each denomination.
U.S. currency denominations (implicit)
def make_change(amount):
return counts
assert make_change(396) == {100: 3, 50: 1, 20: 2, 10: 0, 5: 1, 1: 1}, "Test case 1 failed"
assert make_change(18) == {100: 0, 50: 0, 20: 0, 10: 1, 5: 1, 1: 3}, "Test case 2 failed"
assert make_change(0) == {100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 1: 0}, "Test case 3 failed"
assert make_change(39) == {100: 0, 50: 0, 20: 1, 10: 1, 5: 1, 1: 4}, "Test case 4 failed"
assert make_change(199) == {100: 1, 50: 1, 20: 2, 10: 0, 5: 1, 1: 4}, "Test case 5 failed"
print("All test cases passed successfully")