1. Dictionary
- Dictionaries are actually key-value pairs
- Example: (python concise tutorial)
#!/usr/bin/python # Filename: using_dict.py # 'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]' } print "Swaroop's address is %s" % ab['Swaroop'] # Adding a key/value pair ab['Guido'] = '[email protected]' # Deleting a key/value pair del ab['spammer'] print '\nThere are %d contacts in the address-book\n' % len(ab) for name, address in ab.items(): print 'Contact %s at %s' % (name, address) if 'Guido' in ab: # OR ab.has_key('Guido') print "\nGuido's address is %s" % ab['Guido']
- result:
$ python using_dict.py Swaroop's address is [email protected] There are 4 contacts in the address-book Contact Swaroop at [email protected] Contact Matsumoto at [email protected] Contact Larry at [email protected] Contact Guido at [email protected] Guido's address is [email protected]
-
The items method is used to return a list of tuples, each with keys and values, as in the for loop above
-
The in method or the has_key method can check whether the key exists
- %s it means "this will be replaced with a new string"
- The % in the string will be followed by a letter, which represents the type of variable used to replace, for example %d represents that the variable you will replace here is an integer, and %s represents a string