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
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
{'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
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
pop() method in dictionary
courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
x=courses.pop("HTML")
print(x)
print(courses)
Output
{'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
{'PYTHON': 'Programming', 'HTML': 'Web Designing'}
update() method in dictionary
courses={"PYTHON":"Programming","HTML":"Web Designing","SQL":"Database"}
courses.update({"C++":"Programming"})
print(courses)
Output
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
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
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)