Method for entering data into Dictionaries


In [2]:
## Dealing with duplicate entries. Last value wins!
dict = {'Name': 'Alice', 'Age': 47, 'Name': 'Manni'}
print("dict['Name']: ", dict['Name'])




## Applying Function and Methods
breakfast = {'ham': 'roll', 'egg': 'scramble'}
lunch = {'burger': 'well', 'fries': 'yes', 'salad': 'yes'}
print("Length : %d" % len (lunch))



## seq -- list of values which would be used for dictionary keys preparation.
## value -- if provided then value would be set to this value
seq = ('name', 'height', 'sex')
dict = dict.fromkeys(seq)
print("New Dictionary : %s" %  str(dict)) 
dict = dict.fromkeys(seq, 10,)
print ("New Dictionary : %s" %  str(dict))


dict['Name']:  Manni
Length : 3
New Dictionary : {'name': None, 'height': None, 'sex': None}
New Dictionary : {'name': 10, 'height': 10, 'sex': 10}

Updating values in a Dictionary


In [1]:
## Finding values in a dictionary

dict = {'Name': 'Paisely', 'Age': 27, 'Level': 'Sophomore'}
print(dict['Name'])
print(dict['Age'])



## Finding key that do not exist
## Using a try except clause
dict = {'Name': 'Haley', 'Age': 21, 'Level': 'Junior'}
try:
    dict['Rainbow']
except KeyError:
    print('pass') 



## Updating a Dictionary 
dict = {'Name': 'Paisely', 'Age': 27, 'Level': 'Sophomore'}
dict['Age'] = 19; # update existing dictionay
dict['College'] = "CUNY SPS"; # Add new entry 
print("dict['Age']: ", dict['Age']) 
print ("dict['College']: ", dict['College'])


## Delete Dictionary Elements. 
dict = {'Name': 'Paisely', 'Age': 27, 'Level': 'Sophomore', 'College': 'CUNY SPS'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary
print("dict['Age']: ", dict['Age'])       # will return an error since contents of dict was cleared
print("dict['School']: ", dict['School']) # will return an error since contents of dict was cleared


Paisely
27
pass
dict['Age']:  19
dict['College']:  CUNY SPS
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-dad388e7d105> in <module>()
     30 dict.clear();     # remove all entries in dict
     31 del dict ;        # delete entire dictionary
---> 32 print("dict['Age']: ", dict['Age'])       # will return an error since contents of dict was cleared
     33 print("dict['School']: ", dict['School']) # will return an error since contents of dict was cleared

TypeError: 'type' object is not subscriptable

Finding Values in a Dictionary


In [3]:
## Returns a value for the given key. If key is not available then returns default value None.

dict = {'Name': 'Cheray', 'Age': 27}
print("Value : %s" %  dict.get('Age')) 
print ("Value : %s" %  dict.get('Education', "None"))



## Returns key value pairs as a list of tuples.
dict = {'rank': 'manager', 'Age': 47}
print ("Value : %s" %  dict.items())




## Returns a list of Dictionary keys
dict = {'Room': 2, 'Tutor': 'Jennifer', 'Subject': 'Math'}
print ("Value : %s" %  dict.keys())




## Returns a list of dictionary vlaues
dict = {'Room': 2, 'Tutor': 'Jennifer', 'Subject': 'Math'}
print ("Value : %s" %  dict.values())


Value : 27
Value : None
Value : dict_items([('rank', 'manager'), ('Age', 47)])
Value : dict_keys(['Room', 'Tutor', 'Subject'])
Value : dict_values([2, 'Jennifer', 'Math'])

In [ ]: