Dictionary
Dictionary:
It is a pair of key and value.
# Dictionary
userDictionary = {
"username": "puneet@avahi",
"first_name": "Puneet",
"last_name": "Kumar Singh",
"age": 25,
"is_student": False,
"is_employee": True,
"is_learner": True
}
# Displaying entire dictionary content in one go
print(userDictionary)
# Displaying specific values from the dictionary
# Using the get method to access values it will provide information gracefully.
print(userDictionary.get("username"))
print(userDictionary.get("first_name"))
print(userDictionary.get("last_name"))
# adding value to dictionary
userDictionary["married"] = True
print(userDictionary)
# Length of dictionary
print(len(userDictionary))
# Deleting value from dictionary
# It will remove the key and value from the dictionary
userDictionary.pop("age")
print(userDictionary)
# to clear entire dictionary
userDictionary.clear()
print(userDictionary)
userDictionary["age"] = 25
userDictionary["username"] = "puneet@avahi"
userDictionary["first_name"] = "Puneet"
# want delete only few keys as value
del userDictionary["age"]
print(userDictionary)
# Deleting entire dictionary
del userDictionary
# print(userDictionary) # it will throw error because dictionary is deleted
userDictionary = {
"username": "puneet@avahi",
"first_name": "Puneet",
"last_name": "Kumar Singh",
"age": 25,
"is_student": False,
"is_employee": True,
"is_learner": True
}
for x in userDictionary:
print(x) # it will print the key of dictionary
print(userDictionary[x]) # it will print the value of dictionary
for x,y in userDictionary.items():
print(x,y) # it will print the key of dictionary
# dictionary copy will be as soft copy from one dictionary to another as removal of key
# from one will remove it from another as well.
userDictionary2 = userDictionary
userDictionary2["age"] = 30
print(userDictionary2)
print(userDictionary)
#resolution of this issue
userDictionary2 = userDictionary.copy()
userDictionary2["age"] = 40
print(userDictionary2)
print(userDictionary)
# dictionary is mutable
Assignment:
"""
myVehicle={
"model":"Ford",
"make":"Explorer",
"year":2018,
"mileage":40000
}
create a for loop to print all keys and values.
Create a new varaibel vehicles which is a copy of myVehicle.
Ass a new key 'number_of_tires' to the vehicle2 varaible that is equal to 4
delete the mileage key from the vehicle2 variable
Print just the keys from vehicle2
"""
myVehicle={
"model":"Ford",
"make":"Explorer",
"year":2018,
"mileage":40000
}
for key, value in myVehicle.items():
print(key, value)
vehicles = myVehicle.copy()
vehicles["number_of_tires"] = 4
vehicles.pop("mileage")
print(vehicles.keys())
for keys in vehicles:
print(keys)
Comments
Post a Comment