http://openbookproject.net/thinkcs/python/english3e/dictionaries.html
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"
eng2sp
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco'}
key = 'Five'
eng2sp[key] = 'Sinco'
print(eng2sp)
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco', 'Five': 'Sinco'}
print(eng2sp['One'])
uno
symbolNames = {'*':'asterick', '+':"plus", '-': 'minus'}
print(eng2sp, symbolNames)
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco', 'Five': 'Sinco'} {'*': 'asterick', '+': 'plus', '-': 'minus'}
dict1 ={'one': 'uno', 'two': 'dos', 'three': 'tres', '4': 'quatro', 'five': 'sinco'}
dict1
{'one': 'uno', 'two': 'dos', 'three': 'tres', '4': 'quatro', 'five': 'sinco'}
one = 'One'
eng2sp[one]
'uno'
eng2sp
{'One': 'uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco', 'Five': 'Sinco'}
eng2sp['ten'] = 'diez'
print(eng2sp['ten'])
diez
eng2sp['One'] = 'Uno'
eng2sp
{'One': 'Uno', 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco', 'Five': 'Sinco', 'ten': 'diez'}
eng2sp['One'] = ['uno']
eng2sp['One'].append('Uno')
eng2sp['One'].insert(0, 'UNO')
print(eng2sp)
{'One': ['UNO', 'uno', 0, 'Uno'], 'two': 'dos', 'three': 'tres', 4: 'quatro', 'five': 'sinco', 'Five': 'Sinco', 'ten': 'diez'}
adict = {1: ['uno', 'one'], 2:('two', 'dos'), 3:{'three':'tres'}}
print(adict[2][1])
dos
# How do you access tres in adict?
print(adict[3]['three'])
s
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', 'uno', 0, '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 key Five maps to value Sinco key ten maps to value diez
print(list(eng2sp.keys()))
['One', 'two', 'three', 4, 'five', 'Five', 'ten']
print(list(eng2sp.values()))
[['UNO', 'uno', 0, 'Uno'], 'dos', 'tres', 'quatro', 'sinco', 'Sinco', 'diez']
# iterate over keys
for k in eng2sp:
print('key = {} value = {}'.format(k, eng2sp.get(k)))
key = One value = ['UNO', 'uno', 0, 'Uno'] key = two value = dos key = three value = tres key = 4 value = quatro key = five value = sinco key = Five value = Sinco key = ten value = diez
print(eng2sp.get('asdfsf'))
None
print(eng2sp.get("Ondfe"))
None
# iterate over values
for val in eng2sp.values():
print("value = ", val)
value = ['UNO', 'uno', 0, 'Uno'] value = dos value = tres value = quatro value = sinco value = Sinco value = diez
values = list(eng2sp.values())
values
[['UNO', 'uno', 0, 'Uno'], 'dos', 'tres', 'quatro', 'sinco', 'Sinco', 'diez']
items = list(eng2sp.items())
print(items)
[('One', ['UNO', 'uno', 0, 'Uno']), ('two', 'dos'), ('three', 'tres'), (4, 'quatro'), ('five', 'sinco'), ('Five', 'Sinco'), ('ten', 'diez')]
dict2 = dict(items)
print(dict2)
for k, v in eng2sp.items():
print('{} -> {}'.format(k, v))
print(eng2sp.popitem())
print(eng2sp)
"One" in eng2sp
"Ten" in eng2sp
"twenty" not in eng2sp
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)
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')
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