Friday, January 17, 2025

Python Dictionaries

 A dictionary in python can contain name value pairs. Like

thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
}

where thisdict contains name, gender and age of string, boolean and int data type.

On purpose I have created another dict with a JSON as a value of a name-value pair.

thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
    "assets-json" : {
        "net-worth": 1000000,
        "house-type": "flat",
        "address": ["J P Nagar 5th Ph",
                    "Bangalore",
                    "560034"]
    }
}

I have made use of this dictionary structure in a program which

a. finds the length of the dictionary

b. prints the name, gender and age

c. prints the net-worth of the individual in the dictionary object.


thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
    "assets-json" : {
        "net-worth": 1000000,
        "house-type": "flat",
        "address": ["J P Nagar 5th Ph",
                    "Bangalore",
                    "560034"]
    }
}

thatdict = {
    "name" : "Harish",
    "gender" : True,
    "age" : 54,
    "assets-json" : {
        "net-worth": 10000000,
        "house-type": "Individual House",
        "address": ["Jayanagar",
                    "Bangalore",
                    "560045"]
    }
}

def length_of_dict(dict_param):
    return len(dict_param)

def display_dict(dict_param):
    print("this dict is of %s" % dict_param["name"])
    gender = "male" if dict_param["gender"] == True else "female"
    print("Age = %s \nGender= %s" %(dict_param["age"], gender))
    print("Net Worth:%s" % dict_param["assets-json"]["net-worth"])

if __name__=="__main__":
    print("Length of thatdict:",length_of_dict(thatdict))
    print("Length of thisdict:",length_of_dict(thisdict))
    display_dict(thatdict)
    display_dict(thisdict)

Output of the program:

Length of thatdict: 4

Length of thisdict: 4

this dict is of Harish

Age = 54

Gender= male

Net Worth:10000000

this dict is of Shiva

Age = 45

Gender= male

Net Worth:1000000

No comments:

Post a Comment