#Dictionary
dict={
"Name":"Samruddhi",
"College":"Government Polytechnic Pune",
"Branch":"Computer Engineering",
"City":"Pune"
}
print(dict)
print(type(dict))
print(dict["Name"])
dict["Name"]="Shaurya"
dict["Surname"]="Sahindrakar"
print(dict)
#Nested Dictionary
dict={
"Name":"Samruddhi",
"Age":17,
"Branch":"Computer Engineering",
"Subject Marks":{
"Maths":30,
"Programming in C":30,
"English":27
}
}
#Printing Dictionary, Nested Dict and value of key inside the nested dictionary
print(dict)
print(dict["Subject Marks"])
print(dict["Subject Marks"] ["Maths"])
#Printing the type of the Dictionary, Nested Dict and the value of key inside the
nested dictionary
print(type(dict))
print(type(dict["Subject Marks"]))
print(type(dict["Subject Marks"] ["Maths"]))
# DICTIONARY METHODS
dict={
"Name":"Samruddhi",
"Age":17,
"Branch":"Computer Engineering",
"Subject Marks":{
"Maths":30,
"Programming in C":30,
"English":27
}
}
#DICT.KEYS:
print(dict.keys()) #[Here only outer keys will get displayed not the nested keys]
print(dict["Subject Marks"].keys()) # For printing Nested Keys
print(list(dict.keys())) # For converting into list (only use "()" not "[]" for
type casting)
print(tuple(dict.keys())) # For converting into tuple (only use "()" for type
casting)
print(len(dict.keys())) # For Printing the number (length) of keys in dict
print(len(dict["Subject Marks"].keys())) # For the number of nested keys
#DICT.VALUES:
print(dict.values())
print(dict["Subject Marks"].values())
print(list(dict.values()))
print(tuple(dict["Subject Marks"].values()))
#DICT.ITEMS:
print(dict.items()) # Basically, it returs all the Key:Value Pairs inside the dict
in the form of Tuples.
print(dict["Subject Marks"].items())
print(list(dict.items()))
pairs=list(dict.items()) # Here, assigning all the items to the pairs
print(pairs[0]) # We can access the single pair of item by using index's, as the
tuples are always ordered (properly indexed)
pair2=list(dict["Subject Marks"].items()) #Same with the nested dict pairs
print(pair2[0])
#DICT.GET("key"):
print(dict.get("Name")) #Basically, it returns the value of the particular key
print(dict["Subject Marks"].get("Maths")) #For nested key value
print(dict["Name"]) #This is also the simpler method to access the value but if the
key enterd is undeclared, it
# throws the "Error" due to which further code will not be executed. But if we use
the above method then it will just
# print "none" for the undeclared key.
#DICT.UPDATE(NEW_DICT):
dict.update({"College" : "GPP"}) # For adding the new key:value pair in the dict
print(dict)
dict["Subject Marks"].update({"Physics":29}) # For nested dictionary
print(dict["Subject Marks"])
#OR
new_dict={"State" : "Maharashtra", "Taluka":"Haveli"} # We can also make a new
variable in
#which we can store multiple dictionary values and then update the old one.
dict.update(new_dict)
print(dict)