# Create an empty dictionary eng2sp = dict() eng2sp = {} # equivalent print eng2sp eng2sp['one'] = 'uno' print eng2sp eng2sp['two'] = 'dos' print eng2sp eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} print eng2sp eng2sp = dict([('one', 'uno'), ('two', 'dos'), ('three', 'tres')]) print eng2sp eng = ['one', 'two', 'three'] sp = ['uno', 'dos', 'tres'] dict(TODO) {e:s for e,s in zip(eng, sp) if 'e' in e} eng2sp['three'] eng2sp['five'] if 'five' in eng2sp: print eng2sp['five'] print eng2sp.get('five', "sorry -- no spanish") 6 in [4,5,6,7] True 'two' in {'one':'uno', 'two':'dos', 'three':'tres'} 'dos' in {'one':'uno', 'two':'dos', 'three':'tres'} # Let's add some new value eng2sp['five'] = 'cinco' print eng2sp del eng2sp['five'] print eng2sp eng2sp['five'] = 'cinco' five_sp = eng2sp.pop('five') print five_sp print eng2sp print eng2sp.keys() print eng2sp.values() print eng2sp.items() 'dos' in {'one':'uno', 'two':'dos', 'three':'tres'}.values() def histogram(seq): d = dict() for element in seq: if element not in d: d[element] = 1 else: d[element] += 1 return d h = histogram('brontosaurus') print h def print_hist(hist): for key in hist: print key, hist[key] h = histogram('brontosaurus') print_hist(h) def print_hist(hist): for key, value in hist: print key, value h = histogram('brontosaurus') print_hist(h) def print_hist(hist): for key in sorted(hist.keys()): print key, hist[key] h = histogram('brontosaurus') print_hist(h) def invert_dict(d): # TODO magic, try to come up with 1 line solution sp2eng = invert_dict(eng2sp) assert(sp2eng == {'dos': 'two', 'tres': 'three', 'uno': 'one'}) # some function, this one is just for example def func(x, param=0): print "got x=%s param=%s" % (x, param) # another function which passes majority or all arguments # into func def func2(a, *args, **kwargs): print a, args, kwargs func(*args, **kwargs) func2(1, 'three') func2(1, 'four', param="123")