"""
John Rachlin
DS 2000: Intro to Programming with Data


Date: Mon Oct 24 20:22:02 2022

File: dict_pats.py
    
Description: Patterns for using dictionaries
    
    
"""

#%% Word counting

phrase = "she sells sea shells by the sea shore".split(' ')

#%% Counting Words

wordcount = {}
for word in phrase:
    if word in wordcount:
        wordcount[word] += 1
    else:
        wordcount[word] = 1
print(wordcount)

#%% Printing each key-value pair
def printdict(D):
    for k,v in D.items():
        print(k, v)
    
printdict(wordcount)

#%% Word Length -> Word List

length_dict = {}

for word in phrase:
    length = len(word)
    if length in length_dict:
        length_dict[length].append(word)
    else:
        length_dict[length] = [word]
        
printdict(length_dict)
 

#%% How many words start with each letter??
lettercount = {}
with open("words.txt", "r") as infile:
    for word in infile:
        word = word.strip()
        first = word[0]
        if first in lettercount:
            lettercount[first] += 1
        else:
            lettercount[first] = 1
            
printdict(lettercount)


#%% Tuples are immutable lists

employee = ('Smith', 25, True)
employee[0]
employee2 = ('Jones', 37, False)

employee[0] = 'Jones'

#%% Tuples can be keys - lists cant

bonus = {}
bonus[employee] = 25000
bonus[employee2] = 500
bonus
       
printdict(bonus)

#%% Using get to avoid testing key in dictionary
D = {'a':4, 'b':5, 'c':6}


# method 1
key = 'z'
if key in D:
    D[key] += 1
else:
    D[key] = 1
    
D

#%% Method 2
D = {'a':4, 'b':5, 'c':6}


key = 'b'
D[key] = D.get(key, 0) + 1  
D

#%%  How frequent are different letters among 5-letter words?

wordle_dict = {} # letter -> occurrence counter
with open('words.txt', 'r') as infile:
    for word in infile:
        word = word.strip()
        if len(word) == 5:
            for letter in word:
                wordle_dict[letter] = wordle_dict.get(letter, 0) + 1
                
wordle_dict                 
  
#%% Sort by value
wlist = list(wordle_dict.items())
wlist.sort(key = lambda t: t[1], reverse=True)
wlist[:5]
                    
                    
                    
                    
