27 May 2008

Dictionaries and list comprehension


>>> di = {'joao':['blue', '009']}
>>> di
{'joao': ['blue', '009']}

>>> di = {'jan':['white', '001']}
>>> di
{'jan': ['white', '001']}

>>> di['joao'] = ['blue', '009']
>>> di
{'jan': ['white', '001'], 'joao': ['blue', '009']}

>>> print di
{'jan': ['white', '001'], 'joao': ['blue', '009']}
>>> for item in di:
... print item
...
jan
joao



>>> for i,j in di.iteritems():
... print i,j
...
jan ['white', '001']
joao ['blue', '009']
>>> for i,j in di.iteritems():
... print j
...
['white', '001']
['blue', '009']
>>> for i,j in di.iteritems():
... print j[1]
...
001
009
>>>



######## list comprehension
>>> for person, (color, code) in di.iteritems():
... print "%s likes %s and has code %s" % (person, color, code)
...
jan likes white and has code 001
joao likes blue and has code 009


>>> for person, (color, code) in di.iteritems():
... if color == "blue":
... value = True
...
>>> print value
True
>>> for x, bla in di.iteritems():
... print x
...
jan
joao
>>> for x, bla in di.iteritems():
... print x, bla
...
jan ['white', '001']
joao ['blue', '009']
>>> di
{'jan': ['white', '001'], 'joao': ['blue', '009']}
>>> if "joao" in di:
... print "hi"
...
hi
>>> print "hi5"
File "", line 1
print "hi5"
^
SyntaxError: invalid syntax
>>> if "joao" in di:
... print "hi5"
...
hi5
>>> if "joao" not in di:
... print "hi5"
...
>>> if "joo" not in di:
...
File "", line 2

^
IndentationError: expected an indented block
>>> if "joo" not in di:
... print "hi5"
...
hi5
>>>


adding and removing elements from a dictionary
keys = ['orders','users','textfilter','datefilter']

myData = {}
for key in keys:
myData[key] = None

>>> myData
{'datefilter': None, 'textfilter': None, 'orders': None, 'users': None}

>>> for key in keys:
... myData[key] = [key, key.upper()]
...
>>> myData
{'datefilter': ['datefilter', 'DATEFILTER'], 'textfilter': ['textfilter', 'TEXTFILTER'], 'orders': ['orders', 'ORDERS'], 'users': ['users', 'USERS']}