Understanding dictionary data structure
Table of content
Dictionary
Dictionary is a key-value pair data structure. The key in the dictionary is unique and immutable. The values are mutable. Dictionaries are mutable data structure.
Mutable Data-types --> list,
dictionary, set and user-defined classes.
Immutable Data-types
--> int, float, decimal, bool, string, tuple and range.
How to define dictionary in Python
We define dictionary using curly brackets {}
Access value in dictionary
We can index the key to access the values in dictionary.
Modifying values in dictionary
Adding new key-value pair to the dictionary.
Determining length of Dictionary and checking type of object
Dictionary Functions
1) dict.get(k) : returns the value based on the key passed.
2) dict.keys() : returns the list of keys present in the dictionary.
3) dict.values() : returns list of values present in the dictionary.
4) dict.clear() : removes all the item from dictionary.
5) dict.copy() : returns copy of dictionary.
6) dict.fromkeys(k,v) : returns the dictionary based on key-value provided
passed.
7) dict.items() : returns list of tuple containing key-value pair.
8) dict.pop(k) : removes the key passed and returns value corresponding to it.
Gives KeyError if key is not present in Dictionary. Pop is a fail fast method.
9) dict.update({k:v}): update the value based on the key provided. If key is
not present in the dictionary, It will create new Key-Value Pair. The is a upsert operation.
10) dict.popitem() : returns and removes last added key-value pair as a tuple
and gives KeyError if dictionary is empty.
11) dict.setdefault(k,v) : The setdefault() method returns the value of the
item with the specified key.