map
container, or associative arrays in C++ and other languageseng2sp = {} # or
eng2sp1 = dict()
print(eng2sp, eng2sp1)
{} {}
eng2sp["One"] = "uno"
eng2sp["two"] = "dos"
eng2sp["three"] = "tres"
eng2sp[4] = "quatro"
eng2sp["five"] = "sinco"
key = 'Five'
eng2sp[key] = 'Sinco'
print(eng2sp)
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco'}
print(eng2sp['One'])
uno
symbolNames = {'*':'asterick', '+':"plus", '-': 'minus'}
print(eng2sp, symbolNames)
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco'} {'*': 'asterick', '+': 'plus', '-': 'minus'}
dict1 ={'one': 'uno', 'two': 'dos', 'three': 'tres', '4': 'quatro', 'five': 'sinco'}
one = 'One'
eng2sp[one]
'uno'
eng2sp['ten'] = 'diez'
print(eng2sp['ten'])
diez
eng2sp['One'] = 'Uno'
eng2sp['One'] = ['uno']
eng2sp['One'].append('Uno')
print(eng2sp)
{'One': ['uno', 'Uno'], 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco', 'ten': 'diez', 'one': 'Uno'}
adict = {1: ['uno', 'one'], 2:('two', 'dos'), 3:{'three':'tres'}}
# How do you access tres in adict?
print(adict[1][1])
print(adict[3]['three'])
one tres
help(dict)
Help on class dict in module builtins: class dict(object) | dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs | dict(iterable) -> new dictionary initialized as if via: | d = {} | for k, v in iterable: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) | | Methods defined here: | | __contains__(self, key, /) | True if the dictionary has the specified key, else False. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(...) | D.__sizeof__() -> size of D in memory, in bytes | | clear(...) | D.clear() -> None. Remove all items from D. | | copy(...) | D.copy() -> a shallow copy of D | | get(self, key, default=None, /) | Return the value for key if key is in the dictionary, else default. | | items(...) | D.items() -> a set-like object providing a view on D's items | | keys(...) | D.keys() -> a set-like object providing a view on D's keys | | pop(...) | D.pop(k[,d]) -> v, remove specified key and return the corresponding value. | If key is not found, d is returned if given, otherwise KeyError is raised | | popitem(...) | D.popitem() -> (k, v), remove and return some (key, value) pair as a | 2-tuple; but raise KeyError if D is empty. | | setdefault(self, key, default=None, /) | Insert key with a value of default if key is not in the dictionary. | | Return the value for key if key is in the dictionary, else default. | | update(...) | D.update([E, ]**F) -> None. Update D from dict/iterable E and F. | If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] | If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v | In either case, this is followed by: for k in F: D[k] = F[k] | | values(...) | D.values() -> an object providing a view on D's values | | ---------------------------------------------------------------------- | Class methods defined here: | | fromkeys(iterable, value=None, /) from builtins.type | Create a new dictionary with keys from iterable and values set to value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
for k in eng2sp.keys(): # the order of the keys is not defined
print("key {} maps to value {}".format(k, eng2sp[k]))
key One maps to value uno key two maps to value dos key three maps to value tres key 4 maps to value quatro key five maps to value sinco
# iterate over keys
for k in eng2sp:
print('key = {} value = {}'.format(k, eng2sp[k]))
key = One value = uno key = two value = dos key = three value = tres key = 4 value = quatro key = five value = sinco
# iterate over values
for val in eng2sp.values():
print("value = ", val)
value = uno value = dos value = tres value = quatro value = sinco
values = list(eng2sp.values())
values
['uno', 'dos', 'tres', 'quatro', 'sinco']
items = list(eng2sp.items())
print(items)
[('One', 'uno'), ('two', 'dos'), ('three', 'tres'), (4, 'quatro'), ('five', 'sinco')]
dict2 = dict(items)
print(dict2)
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco'}
for k, v in eng2sp.items():
print('{} -> {}'.format(k, v))
One -> uno two -> dos three -> tres 4 -> quatro five -> sinco
print(eng2sp.popitem())
print(eng2sp)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-19-cc379c436fad> in <module>() ----> 1 print(eng2sp.popitem()) 2 print(eng2sp) KeyError: 'popitem(): dictionary is empty'
"One" in eng2sp
True
"Ten" in eng2sp
False
"twenty" not in eng2sp
True
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
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)
# 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
h = {}
histogram('Mississippim', h)
for k, v in h.items():
print(k, v)
m 2 i 4 s 4 p 2
def getHist(word):# = "Mississippi"
h = {}
for c in word:
if c in h:
h[c] += 1
else:
h[c] = 1
return h
hist = getHist('Mississippi')
print(hist)
if 'M' in hist:
print('M is in histogram')
{'M': 1, 'i': 4, 's': 4, 'p': 2} M is in histogram
Count and print letter frequency in some words. Hint: use get method
Write a program that reads a string and returns a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. 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