Python Selenium

Selenium is a powerful tool for controlling web browser through program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Selenium has four major components – Selenium IDE, Selenium RC, Selenium Web driver, Selenium GRID.

Components-of-Selenium

Selenium Basics

  • Components
  • Features
  • Applications
  • Limitations

Components

Selenium has been in the industry for a long time and used by automation testers all around the globe.
Let’s check the four major components of Selenium

Selenium IDE

Selenium IDE (Integrated Development Environment) is the major tool in the Selenium Suite. It is a complete integrated development environment (IDE) for Selenium tests. It is implemented as a Firefox Add-On and as a Chrome Extension. It allows for recording, editing and debugging of functional tests. It was previously known as Selenium Recorder. Selenium-IDE was originally created by Shinya Kasatani and donated to the Selenium project in 2006. Selenium IDE was previously little-maintained. Selenium IDE began being actively maintained in 2018.

Scripts may be automatically recorded and edited manually providing autocompletion support and the ability to move commands around quickly. Scripts are recorded in Selenese, a special test scripting language for Selenium. Selenese provides commands for performing actions in a browser (click a link, select an option) and for retrieving data from the resulting pages.

Selenium RC (Remote control)

Selenium Remote Control (RC) is a server, written in Java, that accepts commands for the browser via HTTP. RC makes it possible to write automated tests for a web application in any programming language, which allows for better integration of Selenium in existing unit test frameworks. To make writing tests easier, Selenium project currently provides client drivers for PHP, Python, Ruby, .NET, Perl and Java. The Java driver can also be used with JavaScript (via the Rhino engine). An instance of selenium RC server is needed to launch html test case – which means that the port should be different for each parallel run. However, for Java/PHP test case only one Selenium RC instance needs to be running continuously.

Selenium Web Driver

Selenium WebDriver is the successor to Selenium RC. Selenium WebDriver accepts commands (sent in Selenese, or via a Client API) and sends them to a browser. This is implemented through a browser-specific browser driver, which sends commands to a browser and retrieves results. Most browser drivers actually launch and access a browser application (such as Firefox, Google Chrome, Internet Explorer, Safari, or Microsoft Edge); there is also an HtmlUnit browser driver, which simulates a browser using the headless browser HtmlUnit.

Selenium WebDriver does not need a special server to execute tests. Instead, the WebDriver directly starts a browser instance and controls it. However, Selenium Grid can be used with WebDriver to execute tests on remote systems (see below). Where possible, WebDriver uses native operating system level functionality rather than browser-based JavaScript commands to drive the browser. This bypasses problems with subtle differences between native and JavaScript commands, including security restrictions.

Selenium GRID

Selenium Grid is a server that allows tests to use web browser instances running on remote machines. With Selenium Grid, one server acts as the hub. Tests contact the hub to obtain access to browser instances. The hub has a list of servers that provide access to browser instances (WebDriver nodes), and lets tests use these instances. Selenium Grid allows running tests in parallel on multiple machines and to manage different browser versions and browser configurations centrally (instead of in each individual test).

The ability to run tests on remote browser instances is useful to spread the load of testing across several machines and to run tests in browsers running on different platforms or operating systems. The latter is particularly useful in cases where not all browsers to be used for testing can run on the same platform.

Learn from the experts: Create a successful blog with our brand new course

WordPress.com is excited to announce our newest offering: a course just for beginning bloggers where you’ll learn everything you need to know about blogging from the most trusted experts in the industry. We have helped millions of blogs get up and running, we know what works, and we want you to to know everything we know. This course provides all the fundamental skills and inspiration you need to get your blog started, an interactive community forum, and content updated annually.

Python OpenCV

OpenCV is one of the most popular computer vision libraries. If you want to start your journey in the field of computer vision, then a thorough understanding of the concepts of OpenCV is of paramount importance.
In this article, I will try to introduce the most basic and important concepts of OpenCV in an intuitive manner.
This article will cover the following topics:

  1. Reading an image
  2. Extracting the RGB values of a pixel
  3. Extracting the Region of Interest (ROI)
  4. Resizing the Image
  5. Rotating the Image
  6. Drawing a Rectangle
  7. Displaying text

This is the original image that we will manipulate throughout the course of this article.

Original Image

Let’s start with the simple task of reading an image using OpenCV.

Reading an image

Importing the OpenCV library
 import cv2 
 Reading the image using imread() function
 image = cv2.imread('image.png') 
 Extracting the height and width of an image
 h, w = image.shape[:2] 
 Displaying the height and width
 print("Height = {}, Width = {}".format(h, w)) 

Now we will focus on extracting the RGB values of an individual pixel.
Note – OpenCV arranges the channels in BGR order. So the 0th value will correspond to Blue pixel and not Red.

Extracting the RGB values of a pixel

Extracting RGB values.
 Here we have randomly chosen a pixel
 by passing in 100, 100 for height and width.
 (B, G, R) = image[100, 100] 
 Displaying the pixel values
 print("R = {}, G = {}, B = {}".format(R, G, B)) 
 We can also pass the channel to extract
 the value for a specific channel
 B = image[100, 100, 0] 
 print("B = {}".format(B)) 
Region Of Interest

Python MongoDB

MongoDB Python | Insert and Update Data

Prerequisites : MongoDB Python Basics
We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection.

Insert data

We would first insert data in MongoDB.

Step 1 – Establishing Connection: Port number Default: 27017conn = MongoClient(‘localhost’, port-number)If using default port-number i.e. 27017. Alternate connection method:conn = MongoClient()

Step 2 – Create Database or Switch to Existing Database:db = conn.dabasenameCreate a collection or Switch to existing collection:

collection = db.collection_name

Step 3 – Insert : To Insert Data create a dictionary object and insert data in database. Method used to insert data: insert_one() or insert_many()After insert to find the documents inside a collection we use find() command. The find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.
Note : ObjectId is different for every entry in database collection.
Let us understand insert of data with help on code:

# Python code to illustrate 
# inserting data in MongoDB 
from pymongo import MongoClient 
  
try: 
    conn = MongoClient() 
    print("Connected successfully!!!") 
except:   
    print("Could not connect to MongoDB") 
  
# database 
db = conn.database 
  
# Created or Switched to collection names: my_gfg_collection 
collection = db.my_gfg_collection 
  
emp_rec1 = { 
        "name":"Mr.Geek", 
        "eid":24, 
        "location":"delhi"
        } 
emp_rec2 = { 
        "name":"Mr.Shaurya", 
        "eid":14, 
        "location":"delhi"
        } 
  
# Insert Data 
rec_id1 = collection.insert_one(emp_rec1) 
rec_id2 = collection.insert_one(emp_rec2) 
  
print("Data inserted with record ids",rec_id1," ",rec_id2) 
  
# Printing the data inserted 
cursor = collection.find() 
for record in cursor: 
    print(record) 
Connected successfully!!!
Data inserted with record ids    
{'_id': ObjectId('5a02227b37b8552becf5ed2a'), 
'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

Updating data in MongoDB

Methods used: update_one() and update_many()
Parameters passed:
+ a filter document to match the documents to update
+ an update document to specify the modification to perform
+ an optional upsert parameter

# Python code to illustrate 
# updating data in MongoDB 
# with Data of employee with id:24 
from pymongo import MongoClient 
  
try: 
    conn = MongoClient() 
    print("Connected successfully!!!") 
except:   
    print("Could not connect to MongoDB") 
  
# database 
db = conn.database 
  
# Created or Switched to collection names: my_gfg_collection 
collection = db.my_gfg_collection 
  
# update all the employee data whose eid is 24 
result = collection.update_many( 
        {"eid":24}, 
        { 
                "$set":{ 
                        "name":"Mr.Geeksforgeeks"
                        }, 
                "$currentDate":{"lastModified":True} 
                  
                } 
        ) 
  
  
  
print("Data updated with id",result) 
  
# Print the new record 
cursor = collection.find() 
for record in cursor: 
    print(record) 

Output:

Connected successfully!!!
Data updated with id 
{'_id': ObjectId('5a02227b37b8552becf5ed2a'), 
'name': 'Mr.Geeksforgeeks', 'eid': 24, 'location': 
'delhi', 'lastModified': datetime.datetime(2017, 11, 7, 21, 19, 9, 698000)}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

To find number of documents or entries in collection the are updated use.

 print(result.matched_count) 

Python MySQL

Python MySQL – Create Database

Last Updated: 09-03-2020

Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector interface.

Syntax:

CREATE DATABASE DATABASE_NAME
importing rquired libraries
 import mysql.connector 
 dataBase = mysql.connector.connect( 
 host ="localhost", 
 user ="user", 
 passwd ="gfg"
 ) 
 preparing a cursor object
 cursorObject = dataBase.cursor() 
 creating database
 cursorObject.execute("CREATE DATABASE geeks4geeks") 

Output:

python-mysql-create-db

The above program illustrates the creation of MySQL database geeks4geeks in which host-name is localhost, the username is user and password is gfg.

Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a program to create a table in the geeks4geeks database which was created in the above program.

importing required library
 import mysql.connector 
 connecting to the database
 dataBase = mysql.connector.connect( 
                     host = "localhost", 
                     user = "user", 
                     passwd = "gfg", 
                     database = "geeks4geeks" ) 
 preparing a cursor object
 cursorObject = dataBase.cursor() 
 creating table
 studentRecord = """CREATE TABLE STUDENT ( 
                 NAME VARCHAR(20) NOT NULL, 
                 BRANCH VARCHAR(50), 
                 ROLL INT NOT NULL, 
                 SECTION VARCHAR(5), 
                 AGE INT, 
                 )"""
 table created
 cursorObject.execute(studentRecord) 
 disconnecting from server
 dataBase.close() 

Output:

PYTHON-MYSQL-CREATE-DB1

Python CSV

Working with csv files in Python

csv3

This article explains how to load and parse a CSV file in Python.

First of all, what is a CSV ?
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

For working CSV files in python, there is an inbuilt module called csv.

Reading a CSV file

# importing csv module 
import csv 

# csv file name 
filename = "aapl.csv"

# initializing the titles and rows list 
fields = [] 
rows = [] 

# reading csv file 
with open(filename, 'r') as csvfile: 
	# creating a csv reader object 
	csvreader = csv.reader(csvfile) 
	
	# extracting field names through first row 
	fields = next(csvreader) 

	# extracting each data row one by one 
	for row in csvreader: 
		rows.append(row) 

	# get total number of rows 
	print("Total no. of rows: %d"%(csvreader.line_num)) 

# printing the field names 
print('Field names are:' + ', '.join(field for field in fields)) 

# printing first 5 rows 
print('\nFirst 5 rows are:\n') 
for row in rows[:5]: 
	# parsing each column of a row 
	for col in row: 
		print("%10s"%col), 
	print('\n') 

The output of above program looks like this:

csv1

The above example uses a CSV file aapl.csv which can be downloaded from here.
Run this program with the aapl.csv file in same directory.

Let us try to understand this piece of code.

  • with open(filename, ‘r’) as csvfile: csvreader = csv.reader(csvfile)Here, we first open the CSV file in READ mode. The file object is named as csvfile. The file object is converted to csv.reader object. We save the csv.reader object as csvreader.
  • fields = csvreader.next()csvreader is an iterable object. Hence, .next() method returns the current row and advances the iterator to the next row. Since the first row of our csv file contains the headers (or field names), we save them in a list called fields.
  • for row in csvreader: rows.append(row)Now, we iterate through remaining rows using a for loop. Each row is appended to a list called rows. If you try to print each row, one can find that row is nothing but a list containing all the field values.
  • print(“Total no. of rows: %d”%(csvreader.line_num))csvreader.line_num is nothing but a counter which returns the number of rows which have been iterated.

Writing to a CSV file

# importing the csv module 
import csv 

# field names 
fields = ['Name', 'Branch', 'Year', 'CGPA'] 

# data rows of csv file 
rows = [ ['Nikhil', 'COE', '2', '9.0'], 
		['Sanchit', 'COE', '2', '9.1'], 
		['Aditya', 'IT', '2', '9.3'], 
		['Sagar', 'SE', '1', '9.5'], 
		['Prateek', 'MCE', '3', '7.8'], 
		['Sahil', 'EP', '2', '9.1']] 

# name of csv file 
filename = "university_records.csv"

# writing to csv file 
with open(filename, 'w') as csvfile: 
	# creating a csv writer object 
	csvwriter = csv.writer(csvfile) 
	
	# writing the fields 
	csvwriter.writerow(fields) 
	
	# writing the data rows 
	csvwriter.writerows(rows)

Let us try to understand the above code in pieces.

  • fields and rows have been already defined. fields is a list containing all the field names. rows is a list of lists. Each row is a list containing the field values of that row.
  • with open(filename, ‘w’) as csvfile: csvwriter = csv.writer(csvfile)Here, we first open the CSV file in WRITE mode. The file object is named as csvfile. The file object is converted to csv.writer object. We save the csv.writer object as csvwriter.
  • csvwriter.writerow(fields)Now we use writerow method to write the first row which is nothing but the field names.
  • csvwriter.writerows(rows)We use writerows method to write multiple rows at once.

Writing a dictionary to a CSV file

# importing the csv module 
import csv 

# my data rows as dictionary objects 
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, 
		{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, 
		{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, 
		{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, 
		{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, 
		{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] 

# field names 
fields = ['name', 'branch', 'year', 'cgpa'] 

# name of csv file 
filename = "university_records.csv"

# writing to csv file 
with open(filename, 'w') as csvfile: 
	# creating a csv dict writer object 
	writer = csv.DictWriter(csvfile, fieldnames = fields) 
	
	# writing headers (field names) 
	writer.writeheader() 
	
	# writing data rows 
	writer.writerows(mydict) 

In this example, we write a dictionary mydict to a CSV file.

  • with open(filename, ‘w’) as csvfile: writer = csv.DictWriter(csvfile, fieldnames = fields)Here, the file object (csvfile) is converted to a DictWriter object.
    Here, we specify the fieldnames as an argument.
  • writer.writeheader()writeheader method simply writes the first row of your csv file using the pre-specified fieldnames.
  • writer.writerows(mydict)writerows method simply writes all the rows but in each row, it writes only the values(not keys).

So, in the end, our CSV file looks like this:

csv2

Important Points:

  • In csv modules, an optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV format. By default, csv module uses excel dialect which makes them compatible with excel spreadsheets. You can define your own dialect using register_dialect method.
    Here is an example:
     csv.register_dialect(
    'mydialect',
    delimiter = ',',
    quotechar = '"',
    doublequote = True,
    skipinitialspace = True,
    lineterminator = '\r\n',
    quoting = csv.QUOTE_MINIMAL)

Now, while defining a csv.reader or csv.writer object, we can specify the dialect like
this:

csvreader = csv.reader(csvfile, dialect='mydialect')
  • Now, consider that a CSV file looks like this in plain-text:
    We notice that the delimiter is not a comma but a semi-colon. Also, the rows are separated by two newlines instead of one. In such cases, we can specify the delimiter and line terminator as follows:csvreader = csv.reader(csvfile, delimiter = ';', lineterminator = '\n\n')

Python JSON

Introduction of JSON in Python :
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted string which contains value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features.

Python program showing
 use of json package
 import json 
 {key:value mapping}
 a ={"name":"John", 
 "age":31, 
     "Salary":25000} 
 conversion to JSON done by dumps() function
 b = json.dumps(a) 
 printing the output
 print(b) 

Output:

{"age": 31, "Salary": 25000, "name": "John"}

As you can see, JSON supports primitive types, like strings and numbers, as well as nested lists, tuples and objects.

Python program showing that
 json support different primitive
 types
 import json 
 list conversion to Array
 print(json.dumps(['Welcome', "to", "GeeksforGeeks"])) 
 tuple conversion to Array
 print(json.dumps(("Welcome", "to", "GeeksforGeeks"))) 
 string conversion to String
 print(json.dumps("Hi")) 
 int conversion to Number
 print(json.dumps(123)) 
 float conversion to Number
 print(json.dumps(23.572)) 
 Boolean conversion to their respective values
 print(json.dumps(True)) 
 print(json.dumps(False)) 
 None value to null
 print(json.dumps(None)) 

Output:

["Welcome", "to", "GeeksforGeeks"]
["Welcome", "to", "GeeksforGeeks"]
"Hi"
123
23.572
true
false
null

Python Django

Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks.
When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.

django-basics

Why Django?

  • Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time.
  • It’s very easy to switch database in Django framework.
  • It has built-in admin interface which makes easy to work with it.
  • Django is fully functional framework that requires nothing else.
  • It has thousands of additional packages available.
  • It is very scalable. For more visit When to Use Django? Comparison with other Development Stacks ?

Django architecture

Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application.

MVT Structure has the following three parts –

Model: Model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres).

Python Pandas

Pandas is an open-source library that is made mainly for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. This library is built on the top of the NumPy library. Pandas is fast and it has high-performance & productivity for users.

Table of Content

  • History
  • Advantages
  • Getting Started
    • Series
    • DataFrame
  • Why Pandas is used for Data Science

History

Pandas was initially developed by Wes McKinney in 2008 while he was working at AQR Capital Management. He convinced the AQR to allow him to open source the Pandas. Another AQR employee, Chang She, joined as the second major contributor to the library in 2012. Over the time many versions of pandas have been released. The latest version of the pandas is 1.0.1

Advantages

  • Fast and efficient for manipulating and analyzing data.
  • Data from different file objects can be loaded.
  • Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data
  • Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional objects
  • Data set merging and joining.
  • Flexible reshaping and pivoting of data sets
  • Provides time-series functionality.
  • Powerful group by functionality for performing split-apply-combine operations on data sets.

Getting Started

After the pandas has been installed into the system, you need to import the library. This module is generally imported as –

import pandas as pd

Here, pd is referred to as an alias to the Pandas. However, it is not necessary to import the library using alias, it just helps in writing less amount of code everytime a method or property is called.

Python NumPy

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.

Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.

Creating a Numpy Array
Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.

<code># Python program for</code>
<code># Creation of Arrays</code>
<code>import</code> <code>numpy as np</code>
&nbsp;
<code># Creating a rank 1 Array</code>
<code>arr =</code> <code>np.array([1, 2, 3])</code>
<code>print("Array with Rank 1: \n",arr)</code>
&nbsp;
<code># Creating a rank 2 Array</code>
<code>arr =</code> <code>np.array([[1, 2, 3],</code>
<code>[4, 5, 6]])</code>
<code>print("Array with Rank 2: \n", arr)</code>
&nbsp;
<code># Creating an array from tuple</code>
<code>arr =</code> <code>np.array((1, 3, 2))</code>
<code>print("\nArray created using "</code>
<code>"passed tuple:\n", arr)</code>

Output:

Array with Rank 1: 
 [1 2 3]
Array with Rank 2: 
 [[1 2 3]
 [4 5 6]]

Array created using passed tuple:
 [1 3 2]

 
Accessing the array Index
In a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array modifies the original array content.

<code># Python program to demonstrate</code>
<code># indexing in numpy array</code>
<code>import</code> <code>numpy as np</code>
&nbsp;
<code># Initial Array</code>
<code>arr =</code> <code>np.array([[-1, 2, 0, 4],</code>
<code>[4, -0.5, 6, 0],</code>
<code>[2.6, 0, 7, 8],</code>
<code>[3, -7, 4, 2.0]])</code>
<code>print("Initial Array: ")</code>
<code>print(arr)</code>
&nbsp;
<code># Printing a range of Array</code>
<code># with the use of slicing method</code>
<code>sliced_arr =</code> <code>arr[:2, ::2]</code>
<code>print</code> <code>("Array with first 2 rows and"</code>
<code>" alternate columns(0 and 2):\n", sliced_arr)</code>
&nbsp;
<code># Printing elements at</code>
<code># specific Indices</code>
<code>Index_arr =</code> <code>arr[[1, 1, 0, 3], </code>
<code>[3, 2, 1, 0]]</code>
<code>print</code> <code>("\nElements at indices (1, 3), "</code>
<code>"(1, 2), (0, 1), (3, 0):\n", Index_arr)</code>

Output:

Initial Array: 
[[-1.   2.   0.   4. ]
 [ 4.  -0.5  6.   0. ]
 [ 2.6  0.   7.   8. ]
 [ 3.  -7.   4.   2. ]]
Array with first 2 rows and alternate columns(0 and 2):
 [[-1.  0.]
 [ 4.  6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
 [ 0. 54.  2.  3.]

Python Collections

Counter is a container included in the collections module. Now you all must be wondering what is a container. Don’t worry first let’s discuss about the container.

What is Container?

Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built in containers are Tuple, list, and dictionary. Others are included in Collections module.

A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as a dictionary. This is equivalent to a bag or multiset of other languages.

Syntax :

class collections.Counter([iterable-or-mapping])

Initialization :
The constructor of counter can be called in any one of the following ways :

With sequence of itemsWith dictionary containing keys and countsWith keyword arguments mapping string names to counts.

OrderedDict in Python

An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that:

OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.

A Python program to demonstrate working of OrderedDict
 from collections import OrderedDict 
 print("This is a Dict:\n") 
 d = {} 
 d['a'] = 1
 d['b'] = 2
 d['c'] = 3
 d['d'] = 4
 for key, value in d.items(): 
     print(key, value) 
 print("\nThis is an Ordered Dict:\n") 
 od = OrderedDict() 
 od['a'] = 1
 od['b'] = 2
 od['c'] = 3
 od['d'] = 4
 for key, value in od.items(): 
     print(key, value) 

Output:

This is a Dict:
('a', 1)
('c', 3)
('b', 2)
('d', 4)

This is an Ordered Dict:
('a', 1)
('b', 2)
('c', 3)
('d', 4)

Important Points:

  1. Key value Change: If the value of a certain key is changed, the position of the key remains unchanged in OrderedDict.
A Python program to demonstrate working of key
 value change in OrderedDict
 from collections import OrderedDict 
 print("Before:\n") 
 od = OrderedDict() 
 od['a'] = 1
 od['b'] = 2
 od['c'] = 3
 od['d'] = 4
 for key, value in od.items(): 
     print(key, value) 
 print("\nAfter:\n") 
 od['c'] = 5
 for key, value in od.items(): 
     print(key, value) 
Before: ('a', 1) ('b', 2) ('c', 3) ('d', 4) 
After: ('a', 1) ('b', 2) ('c', 5) ('d', 4)

Other Considerations:

  • Ordered dict in Python version 2.7 consumes more memory than normal dict. This is due to the underlying Doubly Linked List implementation for keeping the order. In Python 2.7 Ordered Dict is not dict subclass, it’s a specialized container from collections module.
  • Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.
  • Ordered Dict can be used as a stack with the help of popitem function. Try implementing LRU cache with Ordered Dict.

From Thanh : Software Developer | Devops Engineer | Blog Writer in Germany

Simplify Tasks

Want to learn the simple way?

Chuyện của Nam

Nơi những điều nhỏ bé được khơi dậy

ACE IT SKILLS

From Thanh : Volkswagen Software Developer in Germany

In Dianes Kitchen

Recipes showing step by step directions with pictures and a printable recipe card.

ACE IT SKILLS

From Thanh : Software Developer | Devops Engineer | Blog Writer in Germany

The Daily Post

The Art and Craft of Blogging

The WordPress.com Blog

The latest news on WordPress.com and the WordPress community.