In [ ]:
# Learning Python the Hardway ( 2 weeks/3 weeks)

In [ ]:
# dictionaries
# dict,hashes.
# string,tuples,lists [indexed objects]
# Dictionaries are not indexed objects -> key,value
# apple => red color fruit
# cherry => red color fruit
# apple,cherry(keys) -> unique
# red colour fruit(values)
# SSN,UIN
# json,yaml,pickle..

In [20]:
# Dictionary
# pprint
# dictionary indexes

my_fruits = {'a':'apple','b':'banana','c':'chocolate','d':'dates'}
print my_fruits,type(my_fruits)


{'a': 'apple', 'c': 'chocolate', 'b': 'banana', 'd': 'dates'} <type 'dict'>

In [9]:
# how to read a value provided we have key
print my_fruits['d']


dates

In [3]:
my_empty = {}
print my_empty,type(my_empty)

my_empty = dict()
print my_empty,type(my_empty)


{} <type 'dict'>
{} <type 'dict'>

In [4]:
# insert values into dictionries
my_fruits['f']='figs'
print my_fruits


{'a': 'apple', 'c': 'chocolate', 'b': 'banana', 'd': 'dates', 'f': 'figs'}

In [6]:
# replace
my_fruits['a']=['apricot','apple']
print my_fruits


{'a': ['apricot', 'apple'], 'c': 'chocolate', 'b': 'banana', 'd': 'dates', 'f': 'figs'}

In [10]:
# recursion
# we get keys while running a for loop on a dictionary.

for key in my_fruits:
    print "{} => {}".format(key,my_fruits[key])


a => ['apricot', 'apple']
c => chocolate
b => banana
d => dates
f => figs

In [12]:
# in operation
# in operator works only on keys in a dictionary.
print 'a' in my_fruits
print 'banana' in my_fruits


True
False

In [13]:
# functions
print dir(my_fruits)


['__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', 'viewitems', 'viewkeys', 'viewvalues']

In [15]:
# function
# get
print help(my_fruits.get)
print my_fruits.get('a')
print my_fruits['a']


Help on built-in function get:

get(...)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

None
['apricot', 'apple']
['apricot', 'apple']

In [16]:
# has_key
print help(my_fruits.has_key)
print my_fruits.has_key('a')
print 'a' in my_fruits


Help on built-in function has_key:

has_key(...)
    D.has_key(k) -> True if D has a key k, else False

None
True
True

In [18]:
# keys,iterkeys,viewkeys

#keys
print help(my_fruits.keys)
print my_fruits.keys()


Help on built-in function keys:

keys(...)
    D.keys() -> list of D's keys

None
['a', 'c', 'b', 'd', 'f']

In [19]:
# iterkeys
print help(my_fruits.iterkeys)
print my_fruits.iterkeys()


Help on built-in function iterkeys:

iterkeys(...)
    D.iterkeys() -> an iterator over the keys of D

None
<dictionary-keyiterator object at 0x7f47f0d3c208>

In [20]:
for key in my_fruits.iterkeys():
    print key


a
c
b
d
f

In [3]:
# viewkeys
print help(my_fruits.viewkeys)
print my_fruits.viewkeys()


Help on built-in function viewkeys:

viewkeys(...)
    D.viewkeys() -> a set-like object providing a view on D's keys

None
dict_keys(['a', 'c', 'b', 'd'])

In [6]:
# values,itervalues,viewvalues

# value
print my_fruits.values()

# itevalues
print my_fruits.itervalues()
for value in my_fruits.itervalues():
    print value
    
# viewvalues
print my_fruits.viewvalues()
for value in my_fruits.viewvalues():
    print value


['apple', 'chocolate', 'banana', 'dates']
<dictionary-valueiterator object at 0x7f7878616628>
apple
chocolate
banana
dates
dict_values(['apple', 'chocolate', 'banana', 'dates'])
apple
chocolate
banana
dates

In [8]:
# items,iteritems,viewitems
print my_fruits.items()
print my_fruits.iteritems()
print my_fruits.viewitems()


[('a', 'apple'), ('c', 'chocolate'), ('b', 'banana'), ('d', 'dates')]
<dictionary-itemiterator object at 0x7f7878616788>
dict_items([('a', 'apple'), ('c', 'chocolate'), ('b', 'banana'), ('d', 'dates')])

In [ ]:
# copy
# soft,hard,shallow copy(complex objects)

In [15]:
a = ["one","two","three"]
b = ["four","five","six"]
print id(a),id(b),a,b

Cc = [a,b]
print Cc,id(Cc)
print id(Cc[0]),id(Cc[1]) # the elements of complex objects are refering to a and b.

SOc = Cc
print id(SOc),id(Cc)
print id(Cc[0]),id(Cc[1]),id(SOc[0]),id(SOc[1])
print SOc is Cc
# Any modification to any one a and b should reflect in SOc and Cc.

# deep copy
# two different memory location. any modification in Cc does not refelect in Dc.
import copy
Dc = copy.deepcopy(Cc)
print id(Dc),id(Cc)
print id(Cc[0]),id(Cc[1]),id(Dc[0]),id(Dc[1])

# shallow copy
# its a mix of soft and deep copy.
# external object is deepcopy and internal are softcopy.
print help(copy.copy)

Sc = copy.copy(Cc)  # shallowcopy
print id(Sc),id(Cc)
print Sc is Cc
print id(Cc[0]),id(Cc[1]),id(Sc[0]),id(Sc[1])

#
# traings = [['linux','python','Puppet','django'],['2:00','3:00','4:00','5:00']]  - page1
# costing = [['linux','python','Puppet','django'],['20.00','30.00','40.00','50.00']] - page2


140155392611392 140155392611320 ['one', 'two', 'three'] ['four', 'five', 'six']
[['one', 'two', 'three'], ['four', 'five', 'six']] 140155392611536
140155392611392 140155392611320
140155392611536 140155392611536
140155392611392 140155392611320 140155392611392 140155392611320
True
140155392613048 140155392611536
140155392611392 140155392611320 140155392472560 140155392473280
Help on function copy in module copy:

copy(x)
    Shallow copy operation on arbitrary Python objects.
    
    See the module's __doc__ string for more info.

None
140155392612040 140155392611536
False
140155392611392 140155392611320 140155392611392 140155392611320

In [21]:
# clear
Dmy_fruits = copy.deepcopy(my_fruits)
print Dmy_fruits
print Dmy_fruits.clear()
print Dmy_fruits
print my_fruits


{'a': 'apple', 'c': 'chocolate', 'b': 'banana', 'd': 'dates'}
None
{}
{'a': 'apple', 'c': 'chocolate', 'b': 'banana', 'd': 'dates'}

In [27]:
# pop
print help(my_fruits.pop)
my_fruits.pop('c')
print my_fruits


Help on built-in function pop:

pop(...)
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised

None
{'a': 'apple', 'd': 'dates'}

In [28]:
print my_fruits
my_fruits.pop('c')


{'a': 'apple', 'd': 'dates'}
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-28-3049844b812e> in <module>()
      1 print my_fruits
----> 2 my_fruits.pop('c')

KeyError: 'c'

In [29]:
# my_fruits.popitem
print my_fruits.popitem()


('a', 'apple')

In [24]:
# Project
# https://drive.google.com/file/d/0Bxq4UvUJTuQPMWZKd2d5ZlBoY00/view

In [23]:
my_square = {}
for key in range(1,10):
    my_square[key] = key * key
print my_square.values()


[1, 4, 9, 16, 25, 36, 49, 64, 81]

In [ ]: