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

Ruby on Rails Part 4 - Exception Handling

  Ruby on Rails Part 4 - Exception Handling  Table of content Exception Handling retry raise ensure else  catch and throw Exception classes Exception Handling Enclose the code that could raise an exception with a begin/end block and use rescue clauses to tell Ruby the types of exceptions that you want to handle. The syntax for exception handling : 
 begin  
      #- statements
 rescue OneTypeOfException       #-
 handle the exception rescue AnotherTypeOfException       #- 
handle the exception else       
# Other exceptions
 ensure 
      # ensure block is always executed
 end 
 Everything from begin to rescue is protected 

in the block. 
If an exception occurs during the execution of this block of code, control is passed to the 

block between rescue and end.
 
For each rescue clause in the begin block, Ruby compares the raised Exception against each 

of the parameters of the...