Wednesday, July 8, 2009

python dict

# a dictionary is created with curly braces {}
>>> d = {}
>>> type(d)


# add key,value pairs to the dict
>>> d['adam'] = 123422
>>> d['barry'] = 234223
>>> d['charlie'] = 999322
>>> d
{'barry': 234223, 'adam': 123422, 'charlie': 999322}


# test whether keys are in a dict
>>> 'steve' in d
False
>>> 'barry' in d
True


# iterate through a dict's keys
>>> for k in d.iterkeys():
... print k
...
barry
adam
charlie


# get a key's value from the dict
>>> d.get(k)
999322


# iterate through keys and print out key, value
>>> for k in d.iterkeys():
... print k, " = ", d.get(k)
...
barry = 234223
adam = 123422
charlie = 999322

No comments:

Post a Comment