#!/usr/bin/env python # coding: utf-8 # # 9 Dictionaries # Open In Colab # # http://openbookproject.net/thinkcs/python/english3e/dictionaries.html # # ## Topics # - dictionary data types # - create and use dictionary # - dictionary methods and operations # - dictionary applications and problems # # # ## 9.1 Dictionary # - another compound type/container like lists and tuples # - very useful data structure/container that can store data as lookup table # - Python's mapping type similar to `map` container, or associative arrays in C++ and other languages # - dictionaries maps keys (immutable type) to values of any type (heterogeneous) # - Python uses complex hash algorithm to index key for fast access (Worst case "Big-Oh": $O(1)$) # - as a result the ordering is not maintained # - starting from verion 3.7, python dict remembers the oderes of the elements inserted # ## 9.2 Creating dictionary objects # In[1]: eng2sp = {} # or eng2sp1 = dict() # In[2]: print(eng2sp, eng2sp1) # In[3]: eng2sp["One"] = "uno" eng2sp["two"] = "dos" eng2sp["three"] = "tres" eng2sp[4] = "quatro" eng2sp["five"] = "sinco" # In[4]: eng2sp # In[5]: key = 'Five' eng2sp[key] = 'Sinco' # In[6]: print(eng2sp) # In[7]: print(eng2sp['One']) # In[9]: symbolNames = {'*':'asterick', '+':"plus", '-': 'minus'} # In[10]: print(eng2sp, symbolNames) # In[11]: dict1 ={'one': 'uno', 'two': 'dos', 'three': 'tres', '4': 'quatro', 'five': 'sinco'} # In[12]: dict1 # ## 9.3 Accessing values # - use index operator ['key'] # - dict is mutable # In[14]: one = 'One' # In[15]: eng2sp[one] # In[16]: eng2sp # In[17]: eng2sp['ten'] = 'diez' print(eng2sp['ten']) # In[18]: eng2sp['One'] = 'Uno' # In[19]: eng2sp # In[20]: eng2sp['One'] = ['uno'] # In[21]: eng2sp['One'].append('Uno') # In[25]: eng2sp['One'].insert(0, 'UNO') # In[26]: print(eng2sp) # In[28]: adict = {1: ['uno', 'one'], 2:('two', 'dos'), 3:{'three':'tres'}} # In[35]: print(adict[2][1]) # In[33]: # How do you access tres in adict? print(adict[3]['three']) # ## 9.4 Dictionary methods # In[36]: help(dict) # In[37]: for k in eng2sp.keys(): # the order of the keys is not defined print("key {} maps to value {}".format(k, eng2sp[k])) # In[38]: print(list(eng2sp.keys())) # In[39]: print(list(eng2sp.values())) # In[40]: # iterate over keys for k in eng2sp: print('key = {} value = {}'.format(k, eng2sp.get(k))) # In[43]: print(eng2sp.get('asdfsf')) # In[49]: print(eng2sp.get("Ondfe")) # In[50]: # iterate over values for val in eng2sp.values(): print("value = ", val) # In[51]: values = list(eng2sp.values()) # In[52]: values # In[53]: items = list(eng2sp.items()) # In[54]: print(items) # In[ ]: dict2 = dict(items) print(dict2) # In[ ]: for k, v in eng2sp.items(): print('{} -> {}'.format(k, v)) # In[ ]: print(eng2sp.popitem()) print(eng2sp) # ## 9.5 Checking keys # - in and not in operators can be used to check if some keys exist in a given dictionary # - knowing if key exists helps automatically create dictionaries and access corresponding values # In[ ]: "One" in eng2sp # In[ ]: "Ten" in eng2sp # In[ ]: "twenty" not in eng2sp # ## 9.6 Copying dictionary objects # - shallow copy vs deep copy # In[ ]: import copy digits = {1: 'one', 2: 'two', 3: ['three', 'Three', 'THREE']} digits1 = digits # creates an alias digits2 = digits.copy() # shallow copy digits3 = copy.deepcopy(digits) # deep copy # ### [visualize in pythontutor.com](https://goo.gl/XmvYkB) # In[ ]: from IPython.display import IFrame src = ''' http://pythontutor.com/iframe-embed.html#code=import%20copy%0Adigits%20%3D%20%7B1%3A%20'one',%202%3A%20'two',%203%3A%20%5B'three',%20'Three',%20'THREE'%5D%7D%0Adigits1%20%3D%20digits%20%23%20creates%20an%20alias%0Adigits2%20%3D%20digits.copy%28%29%20%23%20shallow%20copy%0Adigits3%20%3D%20copy.deepcopy%28digits%29%20%23%20deep%20copy&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false ''' IFrame(src, width=900, height=600) # ## 9.7 Passing dictionaries to functions # - dict is a mutable type # - therefore, dict objects are passed by reference # In[ ]: # find the histogram (frequency of each unique character) in a word def histogram(word, hist): for c in word: c = c.lower() if c in hist: hist[c] += 1 else: hist[c] = 1 # In[ ]: h = {} histogram('Mississippim', h) for k, v in h.items(): print(k, v) # ## 9.8 Returning dict from functions # - dict objects can be returned from functions # In[ ]: def getHist(word):# = "Mississippi" h = {} for c in word: if c in h: h[c] += 1 else: h[c] = 1 return h # In[ ]: hist = getHist('Mississippi') print(hist) if 'M' in hist: print('M is in histogram') # ## 9.9 Exercises # 1. Count and print letter frequency in a given word. Hint: use get method # 2. Write a program that reads some text data and prints a frequency table of the letters in alphabetical order. Case should be ignored. A sample output of the program when the user enters the data "ThiS is String with Upper and lower case Letters", would look this: #
# a  2
# c  1
# d  1
# e  5
# g  1
# h  2
# i  4
# l  2
# n  2
# o  1
# p  2
# r  4
# s  5
# t  5
# u  1
# w  2
# 
# ## Kattis problems that can be solved using dict # 1. I've Been Everywhere, Man - https://open.kattis.com/problems/everywhere # - Seven Wonders - https://open.kattis.com/problems/sevenwonders # - ACM Contest Scoring - https://open.kattis.com/problems/acm # - Stacking Cups - https://open.kattis.com/problems/cups # - A New Alphabet - https://open.kattis.com/problems/anewalphabet # - Words for Numbers - https://open.kattis.com/problems/wordsfornumbers # - Babelfish - https://open.kattis.com/problems/babelfish # - Popular Vote - https://open.kattis.com/problems/vote # - Adding Words - https://open.kattis.com/problems/addingwords # - Grandpa Bernie - https://open.kattis.com/problems/grandpabernie # - Judging Troubles - https://open.kattis.com/problems/judging # - Not Amused - https://open.kattis.com/problems/notamused # - Engineering English - https://open.kattis.com/problems/engineeringenglish # - Hardwood Species - https://open.kattis.com/problems/hardwoodspecies # - Conformity - https://open.kattis.com/problems/conformity # - Galactic Collegiate Programming Contest - https://open.kattis.com/problems/gcpc # - Simplicity - https://open.kattis.com/problems/simplicity # In[ ]: