dict
) object is a map that associates keys to values.str
) (like a word in a regular dictionary), a number, or a tuple.{
and }
) or the dict()
function[
and ]
.d = {"A":1,"B":2,"C":3}
empty = {} ## empty dictionary
print(d["A"])
## d[1] won't work; no indices!
## 'in' operator: does a given KEY exist in a dictionary's set of keys?
print("A" in d)
print(1 in d) ## 1 is a value, not a key
print(d.values()) ## print all of the values
print(d.keys()) ## print all of the keys
## convert a tuple to a dictionary:
x = (("A",1),("B",2))
dict(x)
d = {"A":1,"B":2,"C":3}
d["D"]=5 ## add an entry
del d["A"] ## remove an entry
d.pop("C") ## remove an entry *and return its value*
d2 = {"F":5, "G":7, "H":10}
d.update(d2)
print(d)
dict()
functiondict()
dict(A=1,B=2,C=3)
d = dict(A=1,B=2,C=3)
for i in d: ## loop over keys
## do something
print(i)
d.keys()
for k in d:
works about the same as for k in d.keys():
d.items()
(key, value)
tuplesfor i, v in d.items(): ## unpack tuples as we go along
## do something
print(i," maps to", v)
Two equivalent tests:
print(("A",2) in d.items())
print("A" in d and d["A"]==2)
inv = {} ## initialize an empty dictionary
for k in d: ## loop over keys
inv[d[k]] = k ## add d[k] as a key with k as its value
or
inv = {}
for k,v in d.items():
inv[v] = k
number_to_grades
is a dictionary with keys consisting of student numbers and values the (letter) grade for each student in a coursegrades_to_numbers
and would have the set of (letter) grades as its keys and student numbers as its valuesgrade_file.txt
contains a list of student numbers and a letter grade for each student.numbers_to_grades
from this file that has the student numbers as keys and the grades as values.grades_to_numbers
.grades_file = open('grade_file.txt')
number_to_grades = {} ## initialize the dict
for line in grades_file: ## for each line, add the pair
number, grade = tuple(line.split())
number_to_grades[number] = grade
grades_file.close()
## now invert
grades_to_numbers = {} ## intialize the inverted dict
for number, grade in number_to_grades.items():
if grade in grades_to_numbers: # old key
grades_to_numbers[grade].append(number)
else: # new key, so add it (as a one-element list) to the dict
grades_to_numbers[grade] = [number]
dict
rather than a list
to keep track of the number of leading digits found. Remember:def ben_count(file_name):
digits_count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
fn = open(file_name, 'r')
for line in fn:
last_word = get_last_word(line)
leading_digit = get_leading_digit(last_word)
if leading_digit > 0:
digits_count[leading_digit] += 1
fn.close()
return tuple(digits_count)I
replace the list digits_count
with a dictionary
ben_dict = {} # initialize the dict.
fn = open(file_name, 'r')
for line in fn:
last_word = get_last_word(line)
l_d = get_leading_digit(last_word)
if l_d > 0:
if l_d in ben_dict: # l_d is already a key.
ben_dict[l_d] += 1
else: #l_d isn't yet a key.
ben_dict[l_d] = 1
fn.close()