/* */

Thursday, 24 March 2011

String formatting with Dictionaries

phonebook = {'Beth' : '9102' , 'Alice' : '2341' , 'Cecil' : '3228' }
"Cecil's phone number is %(Cecil)s." %phonebook
"Cecil's phone number is 3258."

The (Cecil) points to that particular key, 'phonebook' directs towards the dictionary.

Advantages of Dictionaries over Lists

x = []
x = [42] = 'Foobar'
-error
x = {}
x[42] = 'Foobar'
x
{42 : 'Foobar'}
When we try to assign a value to position 42 in a list it returns an error because items 0-41 dont exist. Because a dictionary relies on mapping rather than sequencing, the key can be created.    

dictionary functions

len(d) - returns number of items (key-value pairs) in d
d[k] - returns the value associated with the key 'k'
d[k]= v - assigns the value 'v' to key 'k'
k in d - checks if the key 'k' is in dictionary 'd'

-dict

The dict function creates a dictionary from other mappings (other dictionaries) or from sequences of pairs (key,value):
items =[('name', 'Jim'), ('age', 42)]
d= dict(items)
d
{'age' : 42, 'name' : 'Jim'}
d['name']
'Jim'

Also can be used with keyword argument:
d= dict(name= 'Jim', age= 42)
d
{'age' : 42,  'name' : 'Jim'}

Wednesday, 23 March 2011

Creating Dictioanries

phonebook = {'Alice' : '2341', 'Beth' : '9102', 'Cecil' : '3258'}

Phone books consist of pairs - their 'key' and irs corresponding item.
e.g. the key 'Alice' has a value of '2341'.
This script has expressed the values as 'strings' and not integeres in order to avoid them being interpreted as octagonal numbers.

Creating an empty dictionary is written:

phonebook = {}

Dictionary - Intro

Dictionaries:
  • refer to value by mapping 'mapping'
  • values don't have an order, but stored in a 'key'
  • 'key's' can be numbers, strings, tuples