Reference; reference

Dictionaries

basic dictionary setup

d = {"A":1,"B":2,"C":3}
empty = {}  ## empty dictionary
print(d["A"])
## d[1] won't work; no indices!

dictionary operations

## '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)

other dictionary operations

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*

updating dictionaries

d2 = {"F":5, "G":7, "H":10}
d.update(d2)
print(d)

the dict() function

dict(A=1,B=2,C=3)

processing a dictionary

d = dict(A=1,B=2,C=3)
for i in d:  ## loop over keys
    ## do something
    print(i)    

dictionary surprises

other dictionary machinery

for i, v in d.items():  ## unpack tuples as we go along
    ## do something
    print(i," maps to", v)

testing for a key/value pair

Two equivalent tests:

print(("A",2) in d.items())
print("A" in d and d["A"]==2)

dictionary inversion

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

more complex inversion

inverting example

inversion

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]

revisiting Benford’s Law

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 list with a dictionary

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()