DEV Community

Ankit Dagar
Ankit Dagar

Posted on

Dictionary Methods of Python

1. items() :-

It gives a list containing a tuple for each key value pair
example:-

>>> thisdict = {
...   "brand": "Ford",
...   "model": "Mustang",
...   "year": 1964
... }
>>> thisdict.items()
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

Enter fullscreen mode Exit fullscreen mode

2. clear() :-

It removes all the elements from the dictionary
example:-

>>> thisdict.clear()
>>> thisdict
{}
Enter fullscreen mode Exit fullscreen mode

3. copy() :-

It gives a copy of the dictionary
example:-

>>> newdict=thisdict.copy()
>>> newdict
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Enter fullscreen mode Exit fullscreen mode

4. fromkeys() :-

it is used to create a new dictionary with keys from the old dictionary list .
example:-

>>> newDict=dict.fromkeys(thisdict,'ankit')
>>> newDict
{'brand': 'ankit', 'model': 'ankit', 'year': 'ankit'}
Enter fullscreen mode Exit fullscreen mode

5. get() :-

It gives the value of the specified key
example:-

>>> newDict.get('brand')
'ankit'
Enter fullscreen mode Exit fullscreen mode

6. keys() :-

It gives a list containing the dictionary's keys
example:-

>>> newDict.keys()
dict_keys(['brand', 'model', 'year'])
Enter fullscreen mode Exit fullscreen mode

7. pop() :-

It removes the element with the specified key
example:-

>>> newdict.pop('brand')
'Ford'
>>> newdict
{'model': 'Mustang', 'year': 1964}
Enter fullscreen mode Exit fullscreen mode

8. popitem() :-

It removes the last inserted key-value pair
example:-

>>> newdict.popitem()
('year', 1964)
>>> newdict
{'model': 'Mustang'}
Enter fullscreen mode Exit fullscreen mode

9. setdefault() :-

It gives the value of the specified key. If the key does not exist: insert the key, with the specified value
example:-

>>> newdict.setdefault('year',1964)
1964
>>> newdict
{'model': 'Mustang', 'year': 1964}
Enter fullscreen mode Exit fullscreen mode

10. update() :-

It updates the dictionary with the specified key-value pairs
example:-

>>> fruits1 = {'apple': 2, 'banana': 3}
>>> fruits2 = {'orange': 4, 'pear': 1}
>>> fruits1.update(fruits2)
>>> fruits1
{'apple': 2, 'banana': 3, 'orange': 4, 'pear': 1}
Enter fullscreen mode Exit fullscreen mode

11. values() :-

It returns a list of all the values in the dictionary
example:-

>>> fruits1
{'apple': 2, 'banana': 3, 'orange': 4, 'pear': 1}
>>> fruits1.values()
dict_values([2, 3, 4, 1])
Enter fullscreen mode Exit fullscreen mode

References

GeeksforGeeks
W3Schools
freecodecamp

Top comments (0)