Python Core



Admission Enquiry Form


Dictionary methods in python

Python has in-built methods for dictionaries.

 

keys() method in dictionary

The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
k=courses.keys()
print(k)



Output

dict_keys(['PYTHON', 'HTML', 'SQL'])



values() method in dictionary

The values() method returns a view object. The view object contains the values of the dictionary, as a list.

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
x=courses.values()
print(x)
print(courses)



Output

dict_values(['Programming', 'Web Designing', 'Database'])
{'PYTHON': 'Programming', 'HTML': 'Web Designing', 'SQL': 'Database'}



get() method in dictionary

The get() method returns the value of the item with the specified key.

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
k=courses.get("SQL")
print(k)


Output

Database



items() method in dictionary

The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
x=courses.items()
print(x)


Output

dict_items([('PYTHON', 'Programming'), ('HTML', 'Web Designing'), ('SQL', 'Database')])



pop() method in dictionary

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
x=courses.pop("HTML")
print(x)
print(courses)


Output

Web Designing
{'PYTHON': 'Programming', 'SQL': 'Database'}



popitem() method in dictionary

The popitem() method removes the item that was last inserted into the dictionary.

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
x=courses.popitem()
print(x)
print(courses)


Output

('SQL', 'Database')
{'PYTHON': 'Programming', 'HTML': 'Web Designing'}



update() method in dictionary

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
courses.update({"C++":"Programming"})
print(courses)


Output

{'PYTHON': 'Programming', 'HTML': 'Web Designing', 'SQL': 'Database', 'C++': 'Programming'}



fromkeys() method in dictionary

The fromkeys() method returns a dictionary with the specified keys and the specified value.

keys=("C","C++","Java")
values="Programming"
courses=dict.fromkeys(keys,values)
print(courses)


Output

{'C': 'Programming', 'C++': 'Programming', 'Java': 'Programming'}






copy() method in dictionary

The copy() method returns a copy of the specified dictionary..

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
cpy=courses.copy()
print(cpy)


Output

{'PYTHON': 'Programming', 'HTML': 'Web Designing', 'SQL': 'Database'}






clear() method in dictionary

The clear() method removes all the elements from a dictionary.

courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
courses.clear()
print(courses)


Output

{}