10/28/2013


In [1]:
a = dict()
b = {}

In [2]:
a['a'] = 'a'
b[0] = 6

In [3]:
len(a)


Out[3]:
1

Dictionaries vs Lists

Iterating over a list gives values.

Iterating over a dictionary gives keys.


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


Iterating through list
1
2
apple
cat
False

 Iterating through dictionary
1
2
3

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


apple
cat
False
OR you can
apple
cat
False

In [10]:
word = "too"
counts = {}
for letter in word:
    if letter in counts:
        counts[letter] = counts[letter] + 1
    else:
        counts[letter] = 1

print counts


{'t': 1, 'o': 2}

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)


{9: ['sid'], 41: ['calvin'], 23: ['tommy', 'susan']}

Global variables

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 [ ]: