In [ ]:
# dictionaries,hashes,dict
# key => value
# keys should not be duplicated, values can be duplicate.
# ex: apple => red color fruit
# ex: cherry => red color fruit
# ex: ssn,uin,

In [1]:
# creation of a dictionary 
my_fruits = {'a':'apple','b':'banana','c':'cherry','d':'dates',2:'twenty'}
print my_fruits,type(my_fruits)
# empty dictionaries
my_empty={}
print my_empty,type(my_empty)
# empty dictionaries
my_empty=dict()
print my_empty,type(my_empty)


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

In [3]:
# cheat sheet
# list - [apple,banana],[],list()
# tuple - (apple,banana),(),tuple()
# dict - {'a':'apple','b':'banana'},{},dict()

In [4]:
# add new value to a dictionary
my_fruits['g'] = 'guava'
print my_fruits


{'a': 'apple', 'c': 'cherry', 'b': 'banana', 'd': 'dates', 'g': 'guava'}

In [27]:
# modify already existing values
my_fruits['g'] = ['grapes','guava']
print my_fruits


{'a': 'apple', 2: 'twenty', 'b': 'banana', 'd': 'dates', 'g': ['grapes', 'guava'], 'c': 'cherry'}

In [8]:
# how to get a value from a key
print my_fruits['a']
print my_fruits['g'][0]


apple
grapes

In [10]:
# in operation
print 'a' in my_fruits
print 'apple' in my_fruits


True
False

In [11]:
# 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 [12]:
# get
print help(my_fruits.get)


Help on built-in function get:

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

None

In [15]:
print my_fruits.get('a')
print my_fruits.get('h')
print my_fruits['a']


apple
None
apple

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


Help on built-in function has_key:

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

None

In [19]:
print my_fruits.has_key('a')
print my_fruits.has_key('apple')
print 'a' in my_fruits
print 'apple' in my_fruits


True
False
True
False

In [21]:
# 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', 2, 'c', 'b', 'd']

In [23]:
# iterkeys
print help(my_fruits.iterkeys)
print my_fruits.iterkeys()
for key in my_fruits.iterkeys():
    print key


Help on built-in function iterkeys:

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

None
<dictionary-keyiterator object at 0x7f2e68532628>
a
2
c
b
d

In [24]:
# 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', 2, 'c', 'b', 'd'])

In [28]:
# values,itervalues,viewvalue
# values
print my_fruits
print help(my_fruits.values)
print my_fruits.values()


{'a': 'apple', 2: 'twenty', 'b': 'banana', 'd': 'dates', 'g': ['grapes', 'guava'], 'c': 'cherry'}
Help on built-in function values:

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

None
['apple', 'twenty', 'banana', 'dates', ['grapes', 'guava'], 'cherry']

In [29]:
# itervalues
print help(my_fruits.itervalues)
print my_fruits.itervalues()


Help on built-in function itervalues:

itervalues(...)
    D.itervalues() -> an iterator over the values of D

None
<dictionary-valueiterator object at 0x7f2e68532940>

In [30]:
# viewvalues
print help(my_fruits.viewvalues)
print my_fruits.viewvalues()


Help on built-in function viewvalues:

viewvalues(...)
    D.viewvalues() -> an object providing a view on D's values

None
dict_values(['apple', 'twenty', 'banana', 'dates', ['grapes', 'guava'], 'cherry'])

In [31]:
# items,iteritems,viewitems

In [32]:
# items
print help(my_fruits.items)
print my_fruits.items()


Help on built-in function items:

items(...)
    D.items() -> list of D's (key, value) pairs, as 2-tuples

None
[('a', 'apple'), (2, 'twenty'), ('b', 'banana'), ('d', 'dates'), ('g', ['grapes', 'guava']), ('c', 'cherry')]

In [33]:
# iteritems
print help(my_fruits.iteritems)
print my_fruits.iteritems()


Help on built-in function iteritems:

iteritems(...)
    D.iteritems() -> an iterator over the (key, value) items of D

None
<dictionary-itemiterator object at 0x7f2e68532ba8>

In [34]:
# viewitems
print help(my_fruits.viewitems)
print my_fruits.viewitems()


Help on built-in function viewitems:

viewitems(...)
    D.viewitems() -> a set-like object providing a view on D's items

None
dict_items([('a', 'apple'), (2, 'twenty'), ('b', 'banana'), ('d', 'dates'), ('g', ['grapes', 'guava']), ('c', 'cherry')])

In [2]:
#'clear', 'copy', 'fromkeys','pop', 'popitem', 'setdefault', 'update'

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


Help on built-in function update:

update(...)
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
    If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
    In either case, this is followed by: for k in F: D[k] = F[k]

None

In [4]:
print my_fruits


{'a': 'apple', 2: 'twenty', 'c': 'cherry', 'b': 'banana', 'd': 'dates'}

In [5]:
my_fruits.update({3:'thirty',4:'fourty','5':'fifty'})

In [6]:
print my_fruits


{'a': 'apple', 2: 'twenty', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}

In [10]:
# 'setdefault'
print help(my_fruits.setdefault)
print my_fruits.setdefault??


Help on built-in function setdefault:

setdefault(...)
    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

None

In [ ]:
print my_fruits.setdefault

In [13]:
my_fruits.setdefault('a',['apple','apricot'])
# my_fruits['a']=['apple','apricot']


Out[13]:
'apple'

In [9]:
print my_fruits


{'a': 'apple', 2: 'twenty', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}

In [11]:
my_fruits.setdefault('j','jackfruit')
print my_fruits


{'a': 'apple', 2: 'twenty', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'j': 'jackfruit', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}

In [12]:
my_fruits.setdefault('j')
# my_fruits['j'] = 'jackfruit'


Out[12]:
'jackfruit'

In [14]:
my_fruits.setdefault('j','jamun')


Out[14]:
'jackfruit'

In [15]:
print my_fruits


{'a': 'apple', 2: 'twenty', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'j': 'jackfruit', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}

In [18]:
# user
my_employee={'labor':500,'manager':50000}
my_oracle={}
my_oracle.setdefault('kumar',my_employee.setdefault('labor'))
my_oracle.setdefault('sai',my_employee.setdefault('labor'))
my_oracle.setdefault('ansh',my_employee.setdefault('manager'))
print my_oracle


{'ansh': 50000, 'kumar': 500, 'sai': 500}

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


Help on built-in function fromkeys:

fromkeys(...)
    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
    v defaults to None.

None

In [21]:
my_new={}
print my_fruits
my_new.fromkeys(my_fruits,10)


{'a': 'apple', 2: 'twenty', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'j': 'jackfruit', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}
Out[21]:
{2: 10, 3: 10, 4: 10, '5': 10, 'a': 10, 'b': 10, 'c': 10, 'd': 10, 'j': 10}

In [22]:
#'pop', 'popitem'
print help(my_fruits.pop)


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

In [24]:
print my_fruits
my_fruits.pop(2)


{'a': 'apple', 2: 'twenty', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'j': 'jackfruit', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}
Out[24]:
'twenty'

In [25]:
print my_fruits
my_fruits.pop(2)


{'a': 'apple', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'j': 'jackfruit', 'c': 'cherry', 3: 'thirty', '5': 'fifty'}
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-25-4a51d03bd8ae> in <module>()
      1 print my_fruits
----> 2 my_fruits.pop(2)

KeyError: 2

In [28]:
# del
del(my_fruits[3])

In [29]:
print my_fruits


{'a': 'apple', 'b': 'banana', 4: 'fourty', 'd': 'dates', 'j': 'jackfruit', 'c': 'cherry', '5': 'fifty'}

In [30]:
del(my_fruits[3])


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-30-c99105937e48> in <module>()
----> 1 del(my_fruits[3])

KeyError: 3

In [31]:
# popitem
print help(my_fruits.popitem)


Help on built-in function popitem:

popitem(...)
    D.popitem() -> (k, v), remove and return some (key, value) pair as a
    2-tuple; but raise KeyError if D is empty.

None

In [32]:
my_fruits.popitem()


Out[32]:
('a', 'apple')

In [33]:
# copy - shallow copy

In [34]:
print help(my_fruits.copy)


Help on built-in function copy:

copy(...)
    D.copy() -> a shallow copy of D

None

In [42]:
new_fruits = my_fruits.copy()
print new_fruits
print new_fruits is my_fruits


{'c': 'cherry', 'b': 'banana', 4: 'fourty', 'd': 'dates', '5': 'fifty', 'j': 'jackfruit'}
False

In [35]:
# shallow copy

In [36]:
a = [1,2,3]
b = [4,5,6]
print id(a),id(b)
print a,b


139904227034464 139904227034608
[1, 2, 3] [4, 5, 6]

In [37]:
# complex object
cob = [a,b]
print cob,cob[0],cob[1]
print id(cob),id(cob[0]),id(cob[1])


[[1, 2, 3], [4, 5, 6]] [1, 2, 3] [4, 5, 6]
139904227034752 139904227034464 139904227034608

In [38]:
# soft copy
soc = cob
print id(cob),id(cob[0]),id(cob[1])
print id(soc),id(soc[0]),id(soc[1])


139904227034752 139904227034464 139904227034608
139904227034752 139904227034464 139904227034608

In [39]:
# deep copy
import copy
doc = copy.deepcopy(cob)
print id(cob),id(cob[0]),id(cob[1])
print id(doc),id(doc[0]),id(doc[1])


139904227034752 139904227034464 139904227034608
139904278705504 139904278704784 139904278785200

In [41]:
# shallow copy
import copy
shc = copy.copy(cob)
print id(cob),id(cob[0]),id(cob[1])
print id(shc),id(shc[0]),id(shc[1])
print "-" * 15,id(a),id(b)


139904227034752 139904227034464 139904227034608
139904212583200 139904227034464 139904227034608
--------------- 139904227034464 139904227034608

In [43]:
# clear
print help(my_fruits.clear)


Help on built-in function clear:

clear(...)
    D.clear() -> None.  Remove all items from D.

None

In [44]:
my_fruits.clear()
print my_fruits


{}

In [ ]: