In [1]:
a = dict()
b = {}
In [2]:
a['a'] = 'a'
b[0] = 6
In [3]:
len(a)
Out[3]:
In [4]:
a = [ 1,2,'apple','cat',False]
b = {1:'apple',2:'cat',3:False}
print "Iterating through list"
for item in a:
print item
print "\n Iterating through dictionary"
for item in b:
print item
Changing the above code to make it work like iterating through a list.
In [5]:
for item in b:
print b[item]
print "OR you can"
for item in b.values():
print item
In [10]:
word = "too"
counts = {}
for letter in word:
if letter in counts:
counts[letter] = counts[letter] + 1
else:
counts[letter] = 1
print counts
In [12]:
ages = {'susan':23,'calvin':41,'tommy':23,'sid':9}
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
print invert_dict(ages)
valid = False
def test(): valid = True print "inside test, after assignment", valid
def test2(): global valid print "inside test2, before assignment", valid valid = True print "inside test2, after assignment", valid
test() print "outside test, after calling test", valid test2() print "outside test2, after calling test", valid
Globals should really only be used "read only"
In [ ]: