Friday, December 15, 2017

Python Dictionaris

So Dictionary allows me to store key-value pair of any data very easily.if you have used JSON in the past then you will be very familiar with the Dictionary in Python.

for example:

student = {

        "name": "Abhinaw"
        "student_id": 20042343
        "feedback": None
}

this is what dictionary looks like in Python.So it has key and value And the value can be of any type.Dictionaries are very helpfull in case ,when you want to store some kind of structured data.

   List of Dictionaries

all_student = [

    {"name:" "Abhinaw" ,"student_id": 20042343},
     {"name:" "Rajat" ,"student_id": 20042345},
{"name:"Gaurav" ,"student_id": 20042893},

]

      Dictionary Data

student["name"] == "Abhinaw"

suppose if you are using key which does not exists in the Dictionary then it will raise an exception called "KeyError" like

student["last_name"] == KeyError

but you can set the default value if key is not present like this

student.get("last_name", "Unknown") == "Unknown".

in case you do not find the last_name in the Dictionary.

if you want all keys in the Dictionary you can simply do like this

student.keys() =["name" ,"student_id" , "feedback"]

student.values() = ["Abhinaw" , 20042343,None]

Similarly you can delete like this

student["name"] = "James"
del student["name"]

No comments: