Monday, January 7, 2013

Python Fundamentals (Sets & Dictionaries)

Here are notes in regards to how Python handles sets and dictionaries as well as how to get built in functions to work utilizing the help section.

List Operations
  • Concatenate -- [1,2] + [3,4] = [1,2,3,4]
  • Append -- list.append()
  • Extend -- list.extend([])
  • Reverse -- list.reverse()
  • Pop -- list.pop()
  • Insert -- list.insert(index, item)
  • Delete -- del list[index]

Sets: unordered collection of unique objects

List to set:
>>> setA = set([1,2,3,3,2])
>>>
>>> setA
set([1, 2, 3])
>>>
>>> setB = set([3,4,5])
>>>
>>> setB
set([3, 4, 5])
>>>

Set operations: Union
>>> setA|setB
set([1, 2, 3, 4, 5])
>>>

Set operations: Intersection
>>> setA&setB
set([3])

Set operations: Difference
>>> setA-setB
set([1, 2])
>>>
>>> setB-setA
set([4, 5])

Dictionaries: unordered key-value pairs which values can change.  Keys are unique and immutable objects.

  • dict = {} (empty dictionary)
  • dict['name'] = 'bob'
  • dict(name='bob', age='33')
  • dict = { 'name' : 'bob', 'age' : 33 }

How to test for alias keys in dictionary.
>>> myInfo
{'hobby': 'hacking', 'age': 33, 'name': 'bob'}
>>> myInfo.has_key('hobby')
True
>>>
>>> myInfo.has_key('hobbies')
False
>>>
>>> 'name' in myInfo
True
>>>

Get a list of keys:
>>> myInfo.keys()
['hobby', 'age', 'name']
>>>

Get a list of values:
>>> myInfo.values()
['hacking', 33, 'chris']
>>>

Get a tuple of items:
>>> myInfo.items()
[('hobby', 'hacking'), ('age', 33), ('name', 'chris')]
>>>

Get a particular item:
>>> myInfo.get('age')
33

How to get built in functions for a particular object.
>>> dir(myInfo)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

Getting help on methods.
>>> help(myInfo.__delattr__)

No comments:

Post a Comment