Dictionary and Set in Python | Shraddha Khapra #Lec 04
# =============== Dictionary and set (built-in data type) =====================
# Dictionaries are used to store to store in key:value paris
# They are unorderd,mutable(changable) & don't allow duplicate keys
dictionary = {
"name" : "asad shams ud din",
"age" : 20,
"class" : "bscs",
"language" : "english,urdu",
"skill":["python","C++","Javascript"], #we can store list in dictionary
"expierence" : ("sotware engineer","data science","machine learning"), #store tuple in dictionary
2004:2025 #we can store like this
}
print(dictionary,type(dictionary))
print(dictionary["age"])
print(dictionary["name"]) #access values in dictionary
dictionary["age"] = 21
print(dictionary) #change values in dictionary
dictionary["location"] = "bahawalpur,punjab,pakistan" #adding new value in dictionary
print(dictionary)
dictionary["language"] = "saraiki" #overwrite
null_dict = {} #create null dictionary
print(null_dict)
# Nested dictionary (dictionary in dictionary)
student = {
"st_name" : "asad",
"p_detail" : {
"cell" : 923055570630,
"mail" : "asadshamsofficial@gmail.com",
"locatiom" : "bahawalpur,punjab,pakistan"
}
}
print(student["p_detail"]["cell"]) #access value in nested dictionary
# ========================= Dictionary Methoed ================================
data = {
"name" : "asad",
"age" : 40
}
#legenth of dictionary
print("legenth of dictionary key : ",len(data.keys()))
# data.keys() #return all keys
print(data.keys())
print(list(data.keys())) #type cast in list convert in list data type we change values across datatype store disctionary in list or list dictionary
#return all values data.values()
print(data.values())
#return all key values as a tuple data.item()
pairs = list(data.items())
print(pairs[0]) #we can covert it into list and also apply list methoeds
#returns the key according the value data.get()
# we have two methoeds to do this opreation
# 1. simple methoed
"""print(data["name2"])""" #if error occur it will give you error
#2. Dictionary methoed
"""print(data.get("name2"))""" #when error occur in this methoed it will return none
# we use the get methoed the major reason is if we got error then our next code will not execute(run) so thats a problem that's why we use get methoed or many other prefrence to get rid from this methoed
# insert the specified item to the dictionary : data.update({new item in dictionary})
#we can update old value with this methoed
"""
print(data.update({"name":"asad shams ud din"})) # we can pass only one argument while use print statment
print(data.update({"is man" : True}))
height= {"height": 163.3}
print(data.update(height)) #we can also store like this
print(data)
"""
# ==================== Sets in Python ===========================
# sets:collection of unordered(index) methoed are called sets
# each item in set are unique and immutable
num = {1,2,3,"asad"} #we can also store string in set
print(num,type(num))
num2 = {1,2,3,2,4} #repeated elements stored only once otherwise set will ignore same values
print(num2)
print(len(num2))#set will not count duplicate values while we check its legenth
null_set = set() #empty set syntax
print(null_set)
# we can print legeenth of set
print(len(num))
# =============================== Set Methoeds ====================================
set7 = set() #sets are mutable bcz we can't change in set values but we can add or remove values in the sets
set7.add(4) #adds an element
set7.add("asad shams ud din") #pass string in set
set7.add((1,2,3,4,5,6,7)) #pass tuple in sets
set7.add(4) #same value cannot be enterd in set
# note: we can't pass list in set bcz our set is mutable
"""set7.add([0,9])""" #error: unhashable type: 'list'
"""print(set7)"""
# imutable = unhashable mean immutable values
# hashing : change original value and convert into in another algorithem
set7.remove(4) #remove an element
"""set7.remove(8)""" #error bcz value does not exits
print(set7)
# empties the set (clear the set) set.clear()
set7.clear()
print(set7)
print(len(set7)) #check the legenth of set after clear methoed it will return 0
print("this is new block of code ouput = ")
# pop methoed in set
# remove random values from sets
new_set = {23,56,78,90,21,66}
print(new_set.pop()) #set.pop()#it deos not take any argument
print(new_set.pop())
# ============================= IMP sets Methoeds =====================================
# Union methoed in sets
set8 = {2,4,5,6,7,8,}
set9 = {3,0,1,8}
union = set8.union(set9) #combines both set values and returns new
print(union)
# Intersection methoed in sets
seta = {"a","d","f","g"}
setb = {"b","a","e","d"}
intersection = seta.intersection(setb) #combines common values and returns new
print(intersection)
# ============================== Lets Practice ==================================
# Qno = 01
# store following words meaning in python dictionary
words = {
"table" : ("a piecec of furniture","list of facts and figure"),
"cat" : "a small animal"
}
print(words)
# Qno = 02
# you are given a list of subjects for students.Assume one classromm is required for 1 subject. How many class needed by all students
# "python","java","c++","python","javascript","java","python","java","c++","c"
subjects = {"python","java","c++","python","javascript","java","python","java","c++","c"}
need_classrom = len(subjects)
print("Room needs for every subjets are : " ,need_classrom)
# Qno = 03
# WAP to enter marks of 3 subjects from the user and store them in dictionary. start with an empty dictionary & add one by one. Use subject name as a key & marks as a value
"""
sub_dictionary = {}
subject1 = int(input("enter your first subject marks = "))
subject2 = int(input("enter your seconed subject marks = "))
subject3 = int(input("enter your third subject marks = "))
sub_dictionary.update({"phy" : subject1})
sub_dictionary.update({"che" : subject2})
sub_dictionary.update({"eng" : subject3})
print(sub_dictionary)
"""
# Qno 04
# Figure out a way to stote 9 and 9.0 as a seprate value in the set (you can take help of built-in data types)
val = {9,"9.0"} #first possible solution
# using built-in data type
set_09 = {
("float",9.0),
("integer",9)
}
print(val)
print(set_09)
Comments
Post a Comment