dictionary
#syntax
myDict = {
"fast": "in a quick manner",
"harry": "A coder",
"marks": [1,2,5],
"anotherDict" : {'harry': 'player'}
}
# print (myDict["fast"])
# print(myDict["harry"])
myDict['marks'] = [45,34]
print(myDict["marks"])
print(myDict['anotherDict']['harry'])
dictionary method
myDict = {
"fast": "in a quick manner",
"harry": "A coder",
"marks": [1,2,5],
"anotherDict" : {'harry': 'player'},
1:2
}
# dictionary meathods
print(list(myDict.keys())) # print the key of the dictionary
print(myDict.values()) # print the key values of the dictionary
print(myDict.items()) # print the (key, values) for all content of the dictionary
print(myDict)
updateDict = {
"lovish": "friend",
2:4,
5:6,
}
myDict.update(updateDict) # update the dictionary by adding pairs updateDict
print(myDict)
print(myDict.get("harry")) # print value associated with "harry"
print(myDict["harry"]) # print value associated with "harry"
# the difference between get and [] syntax in dictionary
print(myDict.get("harry2")) # return none as harry2 is not present in dictionary
print(myDict["harry2"]) # throw an error as harry2 is not present in dictionary
Sets
# set is a Collection of non repetative element
a = {1, 3, 4, 5,1}
print(type(a))
print(a)
# important : This syntax will create an empaty dictionary and not an empty set
a = {}
print(type(a))
# an empty set can be created using the below syntax:
b = set()
print(type(b))
set method
# creating an empty set
b = set()
print(type(b))
# adding values to empty set
b.add(4)
b.add(5)
b.add(4) # adding a value repeatedly does not changes a set
b.add((4,5,6))
# b.add({4,5,6}) # cannot add list or dictionary to set
print(b)
print(len(b)) # print the length of set
# Removal of an item
b.remove(5) # remove 5 from set b
# b.remove(15) # throw an error, because 15 not present in set b
print(b)
print(b.pop())
print(b)
Comments
Post a Comment