The Wayback Machine - https://web.archive.org/web/20241002170056/https://www.geeksforgeeks.org/python-collections-module/
Open In App

Python Collections Module

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will discuss the different containers provided by the collections module.

Table of Content:

Counters

A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable.

Note: It is equivalent to bag or multiset of other languages.

Syntax:

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

Initializing Counter Objects

The counter object can be initialized using the counter() function and this function can be called in one of the following ways:

  • With a sequence of items
  • With a dictionary containing keys and counts
  • With keyword arguments mapping string names to counts

Example:

Python
# A Python program to show different 
# ways to create Counter 
from collections import Counter 
  
# With sequence of items  
print(Counter(['B','B','A','B','C','A','B',
               'B','A','C']))
  
# with dictionary 
print(Counter({'A':3, 'B':5, 'C':2}))
  
# with keyword arguments 
print(Counter(A=3, B=5, C=2))

Output:

Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})

Note: For more information, refer  Counters in Python.

OrderedDict

An OrderedDict is also a sub-class of dictionary but unlike dictionary, it remembers the order in which the keys were inserted. 

Syntax:

class collections.OrderDict()

Example:

Python
# 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
b 2
c 3
d 4

This is an Ordered Dict:

a 1
b 2
c 3
d 4

While deleting and re-inserting the same key will push the key to the last to maintain the order of insertion of the key.

Example:

Python
# A Python program to demonstrate working
# of OrderedDict 

from collections import OrderedDict 


od = OrderedDict() 
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
  
print('Before Deleting')
for key, value in od.items(): 
    print(key, value) 
    
# deleting element
od.pop('a')

# Re-inserting the same
od['a'] = 1

print('\nAfter re-inserting')
for key, value in od.items(): 
    print(key, value)

Output:

Before Deleting
a 1
b 2
c 3
d 4

After re-inserting
b 2
c 3
d 4
a 1

Note: for more information, refer OrderedDict in Python

DefaultDict

A DefaultDict is also a sub-class to dictionary. It is used to provide some default values for the key that does not exist and never raises a KeyError.

Syntax:

class collections.defaultdict(default_factory)

default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised.

Initializing DefaultDict Objects

DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an argument.

Example:

Python
# Python program to demonstrate 
# defaultdict 
   
   
from collections import defaultdict 
   
   
# Defining the dict 
d = defaultdict(int) 
   
L = [1, 2, 3, 4, 2, 4, 1, 2] 
   
# Iterate through the list 
# for keeping the count 
for i in L: 
       
    # The default value is 0 
    # so there is no need to  
    # enter the key first 
    d[i] += 1
       
print(d) 

Output:

defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

Example 2:

Python
# Python program to demonstrate 
# defaultdict 
  
  
from collections import defaultdict 
  
  
# Defining a dict 
d = defaultdict(list) 
  
for i in range(5): 
    d[i].append(i) 
      
print("Dictionary with values as list:") 
print(d) 

Output:

Dictionary with values as list: 
defaultdict(<class ‘list’>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})

Note: For more information, refer Defaultdict in Python

ChainMap

A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.

Syntax:

class collections.ChainMap(dict1, dict2)

Example:

Python
# Python program to demonstrate 
# ChainMap 
   
   
from collections import ChainMap 
   
   
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}

# Defining the chainmap 
c = ChainMap(d1, d2, d3) 
   
print(c)

Output:

ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})

Accessing Keys and Values from ChainMap

Values from ChainMap can be accessed using the key name. They can also be accessed by using the keys() and values() method.

Example:

Python
# Python program to demonstrate 
# ChainMap 
   
   
from collections import ChainMap 
   
   
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}

# Defining the chainmap 
c = ChainMap(d1, d2, d3) 
   
# Accessing Values using key name
print(c['a'])

# Accessing values using values()
# method
print(c.values())

# Accessing keys using keys()
# method
print(c.keys())

Output:


ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6})) 
KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))

Adding new dictionary

A new dictionary can be added by using the new_child() method. The newly added dictionary is added at the beginning of the ChainMap.

Example:

Python
# Python code to demonstrate ChainMap and 
# new_child() 
  
import collections 
  
# initializing dictionaries 
dic1 = { 'a' : 1, 'b' : 2 } 
dic2 = { 'b' : 3, 'c' : 4 } 
dic3 = { 'f' : 5 } 
  
# initializing ChainMap 
chain = collections.ChainMap(dic1, dic2) 
  
# printing chainMap 
print ("All the ChainMap contents are : ") 
print (chain) 
  
# using new_child() to add new dictionary 
chain1 = chain.new_child(dic3) 
  
# printing chainMap
print ("Displaying new ChainMap : ") 
print (chain1) 

Output:

All the ChainMap contents are : 
ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Displaying new ChainMap :
ChainMap({'f': 5}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})

Note: For more information, refer ChainMap in Python

NamedTuple

A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple.

Syntax:

class collections.namedtuple(typename, field_names)

Example:

Python
# Python code to demonstrate namedtuple()
  
from collections import namedtuple
  
# Declaring namedtuple() 
Student = namedtuple('Student',['name','age','DOB']) 
  
# Adding values 
S = Student('Nandini','19','2541997') 
  
# Access using index 
print ("The Student age using index is : ",end ="") 
print (S[1]) 
  
# Access using name  
print ("The Student name using keyname is : ",end ="") 
print (S.name)

Output:

The Student age using index is : 19
The Student name using keyname is : Nandini

Conversion Operations 

1. _make(): This function is used to return a namedtuple() from the iterable passed as argument.

2. _asdict(): This function returns the OrdereDict() as constructed from the mapped values of namedtuple().

Example:

Python
# Python code to demonstrate namedtuple() and 
# _make(), _asdict()
  

from collections import namedtuple
  
# Declaring namedtuple() 
Student = namedtuple('Student',['name','age','DOB']) 
  
# Adding values 
S = Student('Nandini','19','2541997') 
  
# initializing iterable  
li = ['Manjeet', '19', '411997' ] 
  
# initializing dict 
di = { 'name' : "Nikhil", 'age' : 19 , 'DOB' : '1391997' } 
  
# using _make() to return namedtuple() 
print ("The namedtuple instance using iterable is  : ") 
print (Student._make(li)) 
  
# using _asdict() to return an OrderedDict() 
print ("The OrderedDict instance using namedtuple is  : ") 
print (S._asdict()) 

Output:

The namedtuple instance using iterable is  : 
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is :
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])

Note: For more  information, refer NamedTuple in Python

Deque

Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity.

Syntax:

class collections.deque(list)

This function takes the list as an argument.

Example:

Python
# Python code to demonstrate deque
  

from collections import deque
  
# Declaring deque
queue = deque(['name','age','DOB']) 
  
print(queue)

Output:

deque(['name', 'age', 'DOB'])

Inserting Elements

Elements in deque can be inserted from both ends. To insert the elements from right append() method is used and to insert the elements from the left appendleft() method is used.

Example:

Python
# Python code to demonstrate working of  
# append(), appendleft()
  

from collections import deque 
  
# initializing deque 
de = deque([1,2,3]) 
  
# using append() to insert element at right end  
# inserts 4 at the end of deque 
de.append(4) 
  
# printing modified deque 
print ("The deque after appending at right is : ") 
print (de) 
  
# using appendleft() to insert element at right end  
# inserts 6 at the beginning of deque 
de.appendleft(6) 
  
# printing modified deque 
print ("The deque after appending at left is : ") 
print (de) 

Output:

The deque after appending at right is : 
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])

Removing Elements

Elements can also be removed from the deque from both the ends. To remove elements from right use pop() method and to remove elements from the left use popleft() method.

Example:

Python
# Python code to demonstrate working of  
# pop(), and popleft() 

from collections import deque

# initializing deque 
de = deque([6, 1, 2, 3, 4])

# using pop() to delete element from right end  
# deletes 4 from the right end of deque 
de.pop() 
  
# printing modified deque 
print ("The deque after deleting from right is : ") 
print (de) 
  
# using popleft() to delete element from left end  
# deletes 6 from the left end of deque 
de.popleft() 
  
# printing modified deque 
print ("The deque after deleting from left is : ") 
print (de) 

Output:

The deque after deleting from right is : 
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])

Note: For more information, refer Deque in Python.

UserDict

UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality. 

Syntax:

class collections.UserDict([initialdata])

Example:

Python
# Python program to demonstrate 
# userdict 
   
  
from collections import UserDict 
   
  
# Creating a Dictionary where 
# deletion is not allowed 
class MyDict(UserDict): 
      
    # Function to stop deletion 
    # from dictionary 
    def __del__(self): 
        raise RuntimeError("Deletion not allowed") 
          
    # Function to stop pop from  
    # dictionary 
    def pop(self, s = None): 
        raise RuntimeError("Deletion not allowed") 
          
    # Function to stop popitem  
    # from Dictionary 
    def popitem(self, s = None): 
        raise RuntimeError("Deletion not allowed") 
      
# Driver's code 
d = MyDict({'a':1, 
    'b': 2, 
    'c': 3})
  
d.pop(1) 

Output:

Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 32, in <module>
d.pop(1)
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 20, in pop
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in: <bound method MyDict.__del__ of {'a': 1, 'b': 2, 'c': 3}>
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 15, in __del__
RuntimeError: Deletion not allowed

Note: For more information, refer UserDict in Python

UserList

UserList is a list like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality.

Syntax:

class collections.UserList([list])

Example:

Python
# Python program to demonstrate 
# userlist 
   
  
from collections import UserList 
   
  
# Creating a List where 
# deletion is not allowed 
class MyList(UserList): 
      
    # Function to stop deletion 
    # from List 
    def remove(self, s = None): 
        raise RuntimeError("Deletion not allowed") 
          
    # Function to stop pop from  
    # List 
    def pop(self, s = None): 
        raise RuntimeError("Deletion not allowed") 
      
# Driver's code 
L = MyList([1, 2, 3, 4]) 
  
print("Original List") 
  
# Inserting to List" 
L.append(5) 
print("After Insertion") 
print(L) 
  
# Deleting From List 
L.remove() 

Output:

Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
File "/home/c90487eefa7474c0566435269f50a52a.py", line 33, in <module>
L.remove()
File "/home/c90487eefa7474c0566435269f50a52a.py", line 15, in remove
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed

Note: For more information, refer UserList in Python

UserString

UserString is a string like container and just like UserDict and UserList it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality. 

Syntax:

class collections.UserString(seq)

Example:

Python
# Python program to demonstrate 
# userstring 
   
  
from collections import UserString 
   
  
# Creating a Mutable String 
class Mystring(UserString): 
      
    # Function to append to 
    # string 
    def append(self, s): 
        self.data += s 
          
    # Function to remove from  
    # string 
    def remove(self, s): 
        self.data = self.data.replace(s, "") 
      
# Driver's code 
s1 = Mystring("Geeks") 
print("Original String:", s1.data) 
  
# Appending to string 
s1.append("s") 
print("String After Appending:", s1.data) 
  
# Removing from string 
s1.remove("e") 
print("String after Removing:", s1.data)

Output:

Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss

Note: For more information, refer UserString in Python

Python Collections Module – FAQs

How to use the Counter class in the collections module?

The Counter class is a specialized dictionary for counting hashable objects. It is used to count the frequency of elements in an iterable.

Example:

from collections import Counter

# Create a Counter object
c = Counter(['a', 'b', 'c', 'a', 'b', 'a'])

# Output the counts
print(c) # Counter({'a': 3, 'b': 2, 'c': 1})

# Access count of a specific element
print(c['a']) # 3

# Find most common elements
print(c.most_common(2)) # [('a', 3), ('b', 2)]

What is namedtuple and its applications in Python?

namedtuple is a factory function in the collections module that creates tuple subclasses with named fields. It allows you to access elements using named attributes instead of numerical indices.

Example:

from collections import namedtuple

# Define a namedtuple class
Person = namedtuple('Person', ['name', 'age'])

# Create an instance of Person
p = Person(name='John', age=30)

# Access elements using attributes
print(p.name) # John
print(p.age) # 30

Applications:

  • Use namedtuple for data structures where you want to give names to the elements, making the code more readable.
  • Useful for representing records or simple data objects.

How to use defaultdict in Python Collections?

defaultdict is a subclass of the built-in dict class. It provides a default value for missing keys, which avoids KeyError exceptions when accessing or modifying dictionary elements.

Example:

from collections import defaultdict

# Create a defaultdict with default value of int (0)
d = defaultdict(int)

# Increment counts
d['a'] += 1
d['b'] += 2

print(d) # defaultdict(<class 'int'>, {'a': 1, 'b': 2})

# Accessing a missing key returns the default value
print(d['c']) # 0

What are the benefits of using OrderedDict in Python?

OrderedDict is a subclass of the built-in dict that maintains the order of keys based on the order they were first inserted. In Python 3.7 and later, the built-in dict also maintains insertion order, but OrderedDict provides additional features.

Benefits:

  • Order Preservation: Maintains the order of keys as they were added, which is useful for applications requiring ordered data.
  • Reordering: You can move an existing key to either end of the OrderedDict using methods like move_to_end.
  • Equality Comparison: OrderedDict considers the order of keys in equality comparisons, unlike the standard dict.


Similar Reads

Count frequencies of all elements in array in Python using collections module
Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array. Examples: Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] Output : 1 -> 4 2 -> 4 3 -> 2 4 -> 1 5 -> 2 This problem can be solved in many ways, refer Count frequencies of all elements in array link. I
2 min read
Python - Distance between collections of inputs
scipy.stats.cdist(array, axis=0) function calculates the distance between each pair of the two collections of inputs. Parameters : array: Input array or object having the elements to calculate the distance between each pair of the two collections of inputs. axis: Axis along which to be computed. By default axis = 0 Returns : distance between each p
1 min read
Collections.UserList in Python
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Note:
2 min read
Collections.UserDict in Python
An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For more information, refer to Python Dictionary Collect
2 min read
Collections.UserString in Python
Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quote
2 min read
Difference between queue.queue vs collections.deque in Python
Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn't be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they a
3 min read
Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str
2 min read
How to Fix AttributeError: collections has no attribute 'MutableMapping' in Python
The AttributeError: module 'collections' has no attribute 'MutableMapping' error is a common issue encountered by the Python developers especially when working with the older versions of Python or incompatible libraries. This error occurs when attempting to access the MutableMapping class from the collections module in which may not be available in
3 min read
Python - Queue.LIFOQueue vs Collections.Deque
Both LIFOQueue and Deque can be used using in-built modules Queue and Collections in Python, both of them are data structures and are widely used, but for different purposes. In this article, we will consider the difference between both Queue.LIFOQueue and Collections.Deque concerning usability, execution time, working, implementation, etc. in Pyth
3 min read
Get the Names of all Collections using PyMongo
PyMongo is the module used for establishing a connection to the MongoDB using Python and perform all the operations like insertion, deletion, updating, etc. PyMongo is the recommended way to work with MongoDB and Python. Note: For detailed information about Python and MongoDB visit MongoDB and Python. Let's begin with the Get Names of all Collectio
2 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data functi
4 min read
stdev() method in Python statistics module
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. To calculate standard deviation of an entire population, another function known as pstdev() is used. Standard Deviation
5 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
easyinput module in Python
easyinput module in Python offers an easy input interface analogous to cin stream in C++. It supports multiple data types including files and provides functionalities such as input till different data types, multi-line input, etc. Installation To install this module type the below command in the terminal. pip install easyinputFunction Usedread(*typ
3 min read
Python | Adjusting rows and columns of an excel file using openpyxl module
Prerequisites : Excel file using openpyxl writing | reading Set the height and width of the cells:Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimens
3 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
spwd module in Python
spwd module in Python provides access to the Unix shadow password database. The entries stored in the database is tuple-like objects whose attributes are similar as the members of spwd structure defined in <shadow.h> header file. Following are the attributes of tuple-like object which represents the entries stored in Unix shadow password data
5 min read
Practice Tags :