# Dictionaries are used to store data values in key:value pairs
# They are unordered,mutable(changable) & don’t allow duplicate keys
dict={
"name":"Shreya",
"add":"Pune",
"marks":[78,89,45.5,67]
}
print(dict) #output {'name': 'Shreya', 'add': 'Pune', 'marks': [78, 89, 45, 67]}
print(type(dict)) #output <class 'dict'>
# Accessing value
print(dict["name"]) #output Shreya
print(dict["add"]) #output Pune
print(dict["marks"]) #output [78, 89, 45.5, 67]
#Adding new value
dict["surname"]="Sharma"
print(dict) #output {'name': 'Shradha', 'add': 'Pune', 'marks': [78, 89, 45.5, 67],
'surname': 'Sharma'}
#updating value
dict["name"]="Shradha"
print(dict) #output {'name': 'Shradha', 'add': 'Pune', 'marks': [78, 89, 45.5,
67]}
# Removing Items:
# The pop() method removes and returns the value for a specified key,
# while popitem() removes and returns the last inserted key-value pair
surname=dict.pop("surname")
print(dict)
last_item=dict.popitem()
print(dict)
# Dictionary Methods
# 1) clear() #Removes all the elements from the dictionary
fruit = {
"name": "Apple",
"color": "Red",
"price": 250
}
fruit.clear()
print(fruit) #output {}
# 2) copy() Returns a copy of the dictionary
fruit = {
"name": "Apple",
"color": "Red",
"price": 250
}
fruit.copy()
print(fruit) #output {'name': 'Apple', 'color': 'Red', 'price': 250}
# 3)keys() Returns a list containing the dictionary's keys
car={
"name":"Honda City",
"Color":"Black",
"Price":20
}
keys=car.keys()
print(keys) #output dict_keys(['name', 'Color', 'Price'])
# 4) values() Returns a list of all the values in the dictionary
car={
"name":"Honda City",
"Color":"Black",
"Price":20
}
val=car.values()
print(val) #output dict_values(['Honda City', 'Black', 20])
# 5)pop() Removes the element with the specified key
# 6)popitem() Removes the last inserted key-value pair
#7) get() Returns the value of the specified key
car={
"name":"Honda City",
"Color":"Black",
"Price":20
}
prc=car.get("Price")
print(prc)