Skip to main content

Python 3 Part 5 - Understanding dictionay data structure

 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 {}

We can index the key to access the values in dictionary. 

Modifying values in dictionary

 
Deleting key:value pair using del statement.

 

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.


Thank you folks. If you like this Python 3 post, please do checkout my other post on  Django with Python 3 series

Most viewed

Understanding ASCII / Unicode character encoding format

Computer stores everything in binary format. The process of converting a value into binary is called Encoding and the the process of converting value from binary is called Decoding. value --> binary  ::     Encoding  binary --> value   ::    Decoding for example: A number 12 is stored in its binary format as below.               12 ---> 00001100 but how are the characters are stored? If we want to store a character 'a' what formatting should be used ? It easiest way is to map the characters to number and store the binary format of that number. So, the character 'a' is represented as number 97 is stored as 1100001.  ASCII: In ASCII encoding format, 128 unique characters are identified and mapped with numbers (mostly English). One byte is used to represent all the characters. It uses 7 bits to represent numeric value 0 to 127 (total 128 characters).  The most significant bit is a...