Tuesday, June 12, 2018

Dictionaries in Python



What is Dictionaries? 


Unordered collection of key-values Pairs.

It allows you to store and retrieve elements bye referencing a key.

Dictionaries are referenced by key , they have very fast lookup .

Dictionaries are primarily used for referencing items by key.

Dictionaries are not sorted

Examples:

myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

print(myDis) # Output { “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green” } 



Add a item:


myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

myDis[“orange”] = “orange”

print(myDis) # Output:{ “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green”, “orange”: “orange” }




In-built function: dict()


To create a dictionary

mydis = dict( “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green” )

print(myDis) # Output { “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green” } 



In-built function: del()


delete a dicitonry items:

myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

del(myDis[“chilly”] )

print(myDis) # Output:{ “Mango” : ”yellow”, “Apple” : “red” } 




In-built function: len()


myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

print(len(myDis)) # Output: 3





Prev: Sets In Python

Next: Type Conversion in Python

No comments:

Post a Comment

Google+ Followers