Friday, December 14, 2018

Python Dictionary

Dictionary in Python


It is an ordered collection of items. If you look at the other data structures of Python(i.e. list,tuple) they consist only value items, but Dictionary consists of Key,Value pair. As Python dynamically typed language there are no need to define variable type. We can directly define variable name.

We can create dictionary by below commands.

#Empty dictionary 
my_collections = {}


#Dictionary with same type of key
my_collections  = {1:'Rahul',2:'Shayam'}

#Dictionary with different type of keys
my_collections  = {'name':'Rahul',2:[2,3,4]}

We can access the dictionary by below commands.

my_collections1  = {1:'Rahul',2:'Shayam'}
my_collections2  = {'name':'Rahul',2:[2,3,4]}

my_collections1 [1]
my_collections2  ['name']

or

my_collections2 .get('name')

We can add/update the dictionary by below commands.

#update
my_collections2  ['name'] = 'John'

#add
my_collections2 ['age']= 23

We can delete/remove the dictionary by below commands.

cubes= {1:1, 2:8 3:27, 4:64, 5:125}

#Deleting particular item
cubes.pop(4)

#Deleting arbitrary item
cubes.popitem()

#Clearing Dictionary 
cubes.clear()



No comments:

Post a Comment