Dictionary in Python

# how to create blank dictionary
dictionary = {}
print(dictionary)
# declare dictionary with key and value
dictionary = {"fname": "avni","mname":"singh","lname":"rathor"}
print(dictionary)
# accessing key and value from dictionary
for key in dictionary:
    print(key)
    print(dictionary[key])
# accessing key and value with items method
for key,value in dictionary.items():
    print(key,value)
#  value can also be fetched from get method
print(dictionary["fname"])
print(dictionary.get("fname"))

# now will add key and value in dictionary .
dictionary["age"] = "31"
print(dictionary)
# now removing item fname  from dictionary
dictionary.pop("fname")
print(dictionary)
# del keyword can also be used del
del dictionary["lname"]
print(dictionary)
# can clear dictionary with clear function
dictionary.clear()
print(dictionary)
# dict constructior can also be used to make dictionary .

dictionary = dict(name= "abhishek",mname= "pratap singh" ,lname= "rathor")
print(dictionary)
# printing only values
print(dictionary.values())
#printing only keys
print(dictionary.keys())
# updating a dictionary
dictionary.update({"name":"test"})
print(dictionary)
# after executing above print function ,output will be like as below .
{}
{'lname': 'rathor', 'mname': 'singh', 'fname': 'avni'}
lname
rathor
mname
singh
fname
avni
('lname', 'rathor')
('mname', 'singh')
('fname', 'avni')
avni
avni
{'lname': 'rathor', 'mname': 'singh', 'age': '31', 'fname': 'avni'}
{'lname': 'rathor', 'mname': 'singh', 'age': '31'}
{'mname': 'singh', 'age': '31'}
{}
{'lname': 'rathor', 'mname': 'pratap singh', 'name': 'abhishek'}
['rathor', 'pratap singh', 'abhishek']
['lname', 'mname', 'name']
{'lname': 'rathor', 'mname': 'pratap singh', 'name': 'test'}

Comments

Popular posts from this blog

Install Mysql from ZIP without MySQL Installer or Exe

Logging in Python .