Python Data Persistence – Useful Resources

Python Data Persistence – Useful Resources ”; Previous Next The following resources contain additional information on Python Data Persistence. Please use them to get more in-depth knowledge on this. Useful Video Courses Python Data Science Course With Numpy, Pandas, and Matplotlib Best Seller 64 Lectures 6 hours Abhilash Nelson More Detail Data Science, Machine Learning, Data Analysis, Python & R 15 Lectures 8 hours DATAhill Solutions Srinivas Reddy More Detail Python Data Types Course – Fundamentals of Programming in Python 11 Lectures 1 hours Frahaan Hussain More Detail Python Course For Data Science and Machine Learning Featured 141 Lectures 22.5 hours Juan Galvan More Detail Python Data Analysis with Pandas 40 Lectures 2 hours Fanuel Mapuwei More Detail Master Python Data Analysis and Modelling Essentials 35 Lectures 7 hours Shouke Wei More Detail Print Page Previous Next Advertisements ”;

Python Data Persistence – XML Parsers

Python Data Persistence – XML Parsers ”; Previous Next XML is acronym for eXtensible Markup Language. It is a portable, open source and cross platform language very much like HTML or SGML and recommended by the World Wide Web Consortium. It is a well-known data interchange format, used by a large number of applications such as web services, office tools, and Service Oriented Architectures (SOA). XML format is both machine readable and human readable. Standard Python library”s xml package consists of following modules for XML processing − Sr.No. Modules & Description 1 xml.etree.ElementTree the ElementTree API, a simple and lightweight XML processor 2 xml.dom the DOM API definition 3 xml.dom.minidom a minimal DOM implementation 4 xml.sax SAX2 interface implementation 5 xml.parsers.expat the Expat parser binding Data in the XML document is arranged in a tree-like hierarchical format, starting with root and elements. Each element is a single node in the tree and has an attribute enclosed in <> and </> tags. One or more sub-elements may be assigned to each element. Following is a typical example of a XML document − <?xml version = “1.0” encoding = “iso-8859-1″?> <studentlist> <student> <name>Ratna</name> <subject>Physics</subject> <marks>85&lt/marks> </student> <student> <name>Kiran</name> <subject>Maths</subject> <marks>100</marks> </student> <student> <name>Mohit</name> <subject>Biology&lt/subject> <marks>92</marks> </student> </studentlist> While using ElementTree module, first step is to set up root element of the tree. Each Element has a tag and attrib which is a dict object. For the root element, an attrib is an empty dictionary. import xml.etree.ElementTree as xmlobj root=xmlobj.Element(”studentList”) Now, we can add one or more elements under root element. Each element object may have SubElements. Each subelement has an attribute and text property. student=xmlobj.Element(”student”) nm=xmlobj.SubElement(student, ”name”) nm.text=”name” subject=xmlobj.SubElement(student, ”subject”) nm.text=”Ratna” subject.text=”Physics” marks=xmlobj.SubElement(student, ”marks”) marks.text=”85” This new element is appended to the root using append() method. root.append(student) Append as many elements as desired using above method. Finally, the root element object is written to a file. tree = xmlobj.ElementTree(root) file = open(”studentlist.xml”,”wb”) tree.write(file) file.close() Now, we see how to parse the XML file. For that, construct document tree giving its name as file parameter in ElementTree constructor. tree = xmlobj.ElementTree(file=”studentlist.xml”) The tree object has getroot() method to obtain root element and getchildren() returns a list of elements below it. root = tree.getroot() children = root.getchildren() A dictionary object corresponding to each sub element is constructed by iterating over sub-element collection of each child node. for child in children: student={} pairs = child.getchildren() for pair in pairs: product[pair.tag]=pair.text Each dictionary is then appended to a list returning original list of dictionary objects. SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX requires ContentHandler by subclassing xml.sax.ContentHandler. You register callbacks for events of interest and then, let the parser proceed through the document. SAX is useful when your documents are large or you have memory limitations as it parses the file as it reads it from disk as a result entire file is never stored in the memory. Document Object Model (DOM) API is a World Wide Web Consortium recommendation. In this case, entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX, not as fast as DOM, with large files. On the other hand, DOM can kill resources, if used on many small files. SAX is read-only, while DOM allows changes to the XML file. Print Page Previous Next Advertisements ”;

Python Data Persistence – Object Serialization

Python Data Persistence – Object Serialization ”; Previous Next Python”s built-in file object returned by Python”s built-in open() function has one important shortcoming. When opened with ”w” mode, the write() method accepts only the string object. That means, if you have data represented in any non-string form, the object of either in built-in classes (numbers, dictionary, lists or tuples) or other user-defined classes, it cannot be written to file directly. Before writing, you need to convert it in its string representation. numbers=[10,20,30,40] file=open(”numbers.txt”,”w”) file.write(str(numbers)) file.close() For a binary file, argument to write() method must be a byte object. For example, the list of integers is converted to bytes by bytearray() function and then written to file. numbers=[10,20,30,40] data=bytearray(numbers) file.write(data) file.close() To read back data from the file in the respective data type, reverse conversion needs to be done. file=open(”numbers.txt”,”rb”) data=file.read() print (list(data)) This type of manual conversion, of an object to string or byte format (and vice versa) is very cumbersome and tedious. It is possible to store the state of a Python object in the form of byte stream directly to a file, or memory stream and retrieve to its original state. This process is called serialization and de-serialization. Python’s built in library contains various modules for serialization and deserialization process. Sr.No. Name & Description 1 pickle Python specific serialization library 2 marshal Library used internally for serialization 3 shelve Pythonic object persistence 4 dbm library offering interface to Unix database 5 csv library for storage and retrieval of Python data to CSV format 6 json Library for serialization to universal JSON format Print Page Previous Next Advertisements ”;

Python Data Persistence – Introduction

Python Data Persistence – Introduction ”; Previous Next Overview of Python – Data Persistence During the course of using any software application, user provides some data to be processed. The data may be input, using a standard input device (keyboard) or other devices such as disk file, scanner, camera, network cable, WiFi connection, etc. Data so received, is stored in computer’s main memory (RAM) in the form of various data structures such as, variables and objects until the application is running. Thereafter, memory contents from RAM are erased. However, more often than not, it is desired that the values of variables and/or objects be stored in such a manner, that it can be retrieved whenever required, instead of again inputting the same data. The word ‘persistence’ means “the continuance of an effect after its cause is removed”. The term data persistence means it continues to exist even after the application has ended. Thus, data stored in a non-volatile storage medium such as, a disk file is a persistent data storage. In this tutorial, we will explore various built-in and third party Python modules to store and retrieve data to/from various formats such as text file, CSV, JSON and XML files as well as relational and non-relational databases. Using Python’s built-in File object, it is possible to write string data to a disk file and read from it. Python’s standard library, provides modules to store and retrieve serialized data in various data structures such as JSON and XML. Python’s DB-API provides a standard way of interacting with relational databases. Other third party Python packages, present interfacing functionality with NOSQL databases such as MongoDB and Cassandra. This tutorial also introduces, ZODB database which is a persistence API for Python objects. Microsoft Excel format is a very popular data file format. In this tutorial, we will learn how to handle .xlsx file through Python. Print Page Previous Next Advertisements ”;

File Handling with os Module

File Handling with os Module ”; Previous Next In addition to File object returned by open() function, file IO operations can also be performed using Python”s built-in library has os module that provides useful operating system dependent functions. These functions perform low level read/write operations on file. The open() function from os module is similar to the built-in open(). However, it doesn”t return a file object but a file descriptor, a unique integer corresponding to file opened. File descriptor”s values 0, 1 and 2 represent stdin, stdout, and stderr streams. Other files will be given incremental file descriptor from 2 onwards. As in case of open() built-in function, os.open() function also needs to specify file access mode. Following table lists various modes as defined in os module. Sr.No. Os Module & Description 1 os.O_RDONLY Open for reading only 2 os.O_WRONLY Open for writing only 3 os.O_RDWR Open for reading and writing 4 os.O_NONBLOCK Do not block on open 5 os.O_APPEND Append on each write 6 os.O_CREAT Create file if it does not exist 7 os.O_TRUNC Truncate size to 0 8 os.O_EXCL Error if create and file exists To open a new file for writing data in it, specify O_WRONLY as well as O_CREAT modes by inserting pipe (|) operator. The os.open() function returns a file descriptor. f=os.open(“test.dat”, os.O_WRONLY|os.O_CREAT) Note that, data is written to disk file in the form of byte string. Hence, a normal string is converted to byte string by using encode() function as earlier. data=”Hello World”.encode(”utf-8”) The write() function in os module accepts this byte string and file descriptor. os.write(f,data) Don’t forget to close the file using close() function. os.close(f) To read contents of a file using os.read() function, use following statements: f=os.open(“test.dat”, os.O_RDONLY) data=os.read(f,20) print (data.decode(”utf-8”)) Note that, the os.read() function needs file descriptor and number of bytes to be read (length of byte string). If you want to open a file for simultaneous read/write operations, use O_RDWR mode. Following table shows important file operation related functions in os module. Sr.No Functions & Description 1 os.close(fd) Close the file descriptor. 2 os.open(file, flags[, mode]) Open the file and set various flags according to flags and possibly its mode according to mode. 3 os.read(fd, n) Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned. 4 os.write(fd, str) Write the string str to file descriptor fd. Return the number of bytes actually written. Print Page Previous Next Advertisements ”;

Python Data Persistence – Marshal Module

Python Data Persistence – Marshal Module ”; Previous Next Object serialization features of marshal module in Python’s standard library are similar to pickle module. However, this module is not used for general purpose data. On the other hand, it is used by Python itself for Python’s internal object serialization to support read/write operations on compiled versions of Python modules (.pyc files). The data format used by marshal module is not compatible across Python versions. Therefore, a compiled Python script (.pyc file) of one version most probably won’t execute on another. Just as pickle module, marshal module also defined load() and dump() functions for reading and writing marshalled objects from / to file. dump() This function writes byte representation of supported Python object to a file. The file itself be a binary file with write permission load() This function reads the byte data from a binary file and converts it to Python object. Following example demonstrates use of dump() and load() functions to handle code objects of Python, which are used to store precompiled Python modules. The code uses built-in compile() function to build a code object out of a source string which embeds Python instructions. compile(source, file, mode) The file parameter should be the file from which the code was read. If it wasn’t read from a file pass any arbitrary string. The mode parameter is ‘exec’ if the source contains sequence of statements, ‘eval’ if there is a single expression or ‘single’ if it contains a single interactive statement. The compile code object is then stored in a .pyc file using dump() function. import marshal script = “”” a=10 b=20 print (”addition=”,a+b) “”” code = compile(script, “script”, “exec”) f=open(“a.pyc”,”wb”) marshal.dump(code, f) f.close() To deserialize, the object from .pyc file use load() function. Since, it returns a code object, it can be run using exec(), another built-in function. import marshal f=open(“a.pyc”,”rb”) data=marshal.load(f) exec (data) Print Page Previous Next Advertisements ”;

Python Data Persistence – File API

Python Data Persistence – File API ”; Previous Next Python uses built-in input() and print() functions to perform standard input/output operations. The input() function reads bytes from a standard input stream device, i.e. keyboard. The print() function on the other hand, sends the data towards standard output stream device i.e. the display monitor. Python program interacts with these IO devices through standard stream objects stdin and stdout defined in sys module. The input() function is actually a wrapper around readline() method of sys.stdin object. All keystrokes from the input stream are received till ‘Enter’ key is pressed. >>> import sys >>> x=sys.stdin.readline() Welcome to TutorialsPoint >>> x ”Welcome to TutorialsPointn” Note that, readline() function leave a trailing ‘n’ character. There is also a read() method which reads data from standard input stream till it is terminated by Ctrl+D character. >>> x=sys.stdin.read() Hello Welcome to TutorialsPoint >>> x ”HellonWelcome to TutorialsPointn” Similarly, print() is a convenience function emulating write() method of stdout object. >>> x=”Welcome to TutorialsPointn” >>> sys.stdout.write(x) Welcome to TutorialsPoint 26 Just as stdin and stdout predefined stream objects, a Python program can read data from and send data to a disk file or a network socket. They are also streams. Any object that has read() method is an input stream. Any object that has write() method is an output stream. The communication with the stream is established by obtaining reference to the stream object with built-in open() function. open() function This built-in function uses following arguments − f=open(name, mode, buffering) The name parameter, is name of disk file or byte string, mode is optional one-character string to specify the type of operation to be performed (read, write, append etc.) and buffering parameter is either 0, 1 or -1 indicating buffering is off, on or system default. File opening mode is enumerated as per table below. Default mode is ‘r’ Sr.No Parameters & Description 1 R Open for reading (default) 2 W Open for writing, truncating the file first 3 X Create a new file and open it for writing 4 A Open for writing, appending to the end of the file if it exists 5 B Binary mode 6 T Text mode (default) 7 + Open a disk file for updating (reading and writing) In order to save data to file it must be opened with ‘w’ mode. f=open(”test.txt”,”w”) This file object acts as an output stream, and has access to write() method. The write() method sends a string to this object, and is stored in the file underlying it. string=”Hello TutorialsPointn” f.write(string) It is important to close the stream, to ensure that any data remaining in buffer is completely transferred to it. file.close() Try and open ‘test.txt’ using any test editor (such as notepad) to confirm successful creation of file. To read contents of ‘test.txt’ programmatically, it must be opened in ‘r’ mode. f=open(”test.txt”,”r”) This object behaves as an input stream. Python can fetch data from the stream using read() method. string=f.read() print (string) Contents of the file are displayed on Python console. The File object also supports readline() method which is able to read string till it encounters EOF character. However, if same file is opened in ‘w’ mode to store additional text in it, earlier contents are erased. Whenever, a file is opened with write permission, it is treated as if it is a new file. To add data to an existing file, use ‘a’ for append mode. f=open(”test.txt”,”a”) f.write(”Python Tutorialsn”) The file now, has earlier as well as newly added string. The file object also supports writelines() method to write each string in a list object to the file. f=open(”test.txt”,”a”) lines=[”Java Tutorialsn”, ”DBMS tutorialsn”, ”Mobile development tutorialsn”] f.writelines(lines) f.close() Example The readlines() method returns a list of strings, each representing a line in the file. It is also possible to read the file line by line until end of file is reached. f=open(”test.txt”,”r”) while True: line=f.readline() if line==”” : break print (line, end=””) f.close() Output Hello TutorialsPoint Python Tutorials Java Tutorials DBMS tutorials Mobile development tutorials Binary mode By default, read/write operation on a file object are performed on text string data. If we want to handle files of different other types such as media (mp3), executables (exe), pictures (jpg) etc., we need to add ‘b’ prefix to read/write mode. Following statement will convert a string to bytes and write in a file. f=open(”test.bin”, ”wb”) data=b”Hello World” f.write(data) f.close() Conversion of text string to bytes is also possible using encode() function. data=”Hello World”.encode(”utf-8”) We need to use ‘rb’ mode to read binary file. Returned value of read() method is first decoded before printing. f=open(”test.bin”, ”rb”) data=f.read() print (data.decode(encoding=”utf-8”)) In order to write integer data in a binary file, the integer object should be converted to bytes by to_bytes() method. n=25 n.to_bytes(8,”big”) f=open(”test.bin”, ”wb”) data=n.to_bytes(8,”big”) f.write(data) To read back from a binary file, convert output of read() function to integer by from_bytes() function. f=open(”test.bin”, ”rb”) data=f.read() n=int.from_bytes(data, ”big”) print (n) For floating point data, we need to use struct module from Python’s standard library. import struct x=23.50 data=struct.pack(”f”,x) f=open(”test.bin”, ”wb”) f.write(data) Unpacking the string from read() function, to retrieve the float data from binary file. f=open(”test.bin”, ”rb”) data=f.read() x=struct.unpack(”f”, data) print (x)

Python Data Persistence – Shelve Module

Python Data Persistence – Shelve Module ”; Previous Next The shelve module in Python’s standard library provides simple yet effective object persistence mechanism. The shelf object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems. The shelf dictionary has certain restrictions. Only string data type can be used as key in this special dictionary object, whereas any picklable Python object can be used as value. The shelve module defines three classes as follows − Sr.No Shelve Module & Description 1 Shelf This is the base class for shelf implementations. It is initialized with dict-like object. 2 BsdDbShelf This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods. 3 DbfilenameShelf This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object. The open() function defined in shelve module which return a DbfilenameShelf object. open(filename, flag=”c”, protocol=None, writeback=False) The filename parameter is assigned to the database created. Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write). The serialization itself is governed by pickle protocol, default is none. Last parameter writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations, hence process may be slow. Following code creates a database and stores dictionary entries in it. import shelve s=shelve.open(“test”) s[”name”]=”Ajay” s[”age”]=23 s[”marks”]=75 s.close() This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available − Sr.No. Methods & Description 1 close() synchronise and close persistent dict object. 2 sync() Write back all entries in the cache if shelf was opened with writeback set to True. 3 get() returns value associated with key 4 items() list of tuples – each tuple is key value pair 5 keys() list of shelf keys 6 pop() remove specified key and return the corresponding value. 7 update() Update shelf from another dict/iterable 8 values() list of shelf values To access value of a particular key in shelf − s=shelve.open(”test”) print (s[”age”]) #this will print 23 s[”age”]=25 print (s.get(”age”)) #this will print 25 s.pop(”marks”) #this will remove corresponding k-v pair As in a built-in dictionary object, the items(), keys() and values() methods return view objects. print (list(s.items())) [(”name”, ”Ajay”), (”age”, 25), (”marks”, 75)] print (list(s.keys())) [”name”, ”age”, ”marks”] print (list(s.values())) [”Ajay”, 25, 75] To merge items of another dictionary with shelf use update() method. d={”salary”:10000, ”designation”:”manager”} s.update(d) print (list(s.items())) [(”name”, ”Ajay”), (”age”, 25), (”salary”, 10000), (”designation”, ”manager”)] Print Page Previous Next Advertisements ”;

Python Data Persistence – dbm Package

Python Data Persistence – dbm Package ”; Previous Next The dbm package presents a dictionary like interface DBM style databases. DBM stands for DataBase Manager. This is used by UNIX (and UNIX like) operating system. The dbbm library is a simple database engine written by Ken Thompson. These databases use binary encoded string objects as key, as well as value. The database stores data by use of a single key (a primary key) in fixed-size buckets and uses hashing techniques to enable fast retrieval of the data by key. The dbm package contains following modules − dbm.gnu module is an interface to the DBM library version as implemented by the GNU project. dbm.ndbm module provides an interface to UNIX nbdm implementation. dbm.dumb is used as a fallback option in the event, other dbm implementations are not found. This requires no external dependencies but is slower than others. >>> dbm.whichdb(”mydbm.db”) ”dbm.dumb” >>> import dbm >>> db=dbm.open(”mydbm.db”,”n”) >>> db[”name”]=Raj Deshmane” >>> db[”address”]=”Kirtinagar Pune” >>> db[”PIN”]=”431101” >>> db.close() The open() function allows mode these flags − Sr.No. Value & Meaning 1 ”r” Open existing database for reading only (default) 2 ”w” Open existing database for reading and writing 3 ”c” Open database for reading and writing, creating it if it doesn’t exist 4 ”n” Always create a new, empty database, open for reading and writing The dbm object is a dictionary like object, just as shelf object. Hence, all dictionary operations can be performed. The dbm object can invoke get(), pop(), append() and update() methods. Following code opens ”mydbm.db” with ”r” flag and iterates over collection of key-value pairs. >>> db=dbm.open(”mydbm.db”,”r”) >>> for k,v in db.items(): print (k,v) b”name” : b”Raj Deshmane” b”address” : b”Kirtinagar Pune” b”PIN” : b”431101” Print Page Previous Next Advertisements ”;

Python Data Persistence – CSV Module

Python Data Persistence – CSV Module ”; Previous Next CSV stands for comma separated values. This file format is a commonly used data format while exporting/importing data to/from spreadsheets and data tables in databases. The csv module was incorporated in Python’s standard library as a result of PEP 305. It presents classes and methods to perform read/write operations on CSV file as per recommendations of PEP 305. CSV is a preferred export data format by Microsoft’s Excel spreadsheet software. However, csv module can handle data represented by other dialects also. The CSV API interface consists of following writer and reader classes − writer() This function in csv module returns a writer object that converts data into a delimited string and stores in a file object. The function needs a file object with write permission as a parameter. Every row written in the file issues a newline character. To prevent additional space between lines, newline parameter is set to ””. The writer class has following methods − writerow() This method writes items in an iterable (list, tuple or string), separating them by comma character. writerows() This method takes a list of iterables, as parameter and writes each item as a comma separated line of items in the file. Example Following example shows use of writer() function. First a file is opened in ‘w’ mode. This file is used to obtain writer object. Each tuple in list of tuples is then written to file using writerow() method. import csv persons=[(”Lata”,22,45),(”Anil”,21,56),(”John”,20,60)] csvfile=open(”persons.csv”,”w”, newline=””) obj=csv.writer(csvfile) for person in persons: obj.writerow(person) csvfile.close() Output This will create ‘persons.csv’ file in current directory. It will show following data. Lata,22,45 Anil,21,56 John,20,60 Instead of iterating over the list to write each row individually, we can use writerows() method. csvfile=open(”persons.csv”,”w”, newline=””) persons=[(”Lata”,22,45),(”Anil”,21,56),(”John”,20,60)] obj=csv.writer(csvfile) obj.writerows(persons) obj.close() reader() This function returns a reader object which returns an iterator of lines in the csv file. Using the regular for loop, all lines in the file are displayed in following example − Example csvfile=open(”persons.csv”,”r”, newline=””) obj=csv.reader(csvfile) for row in obj: print (row) Output [”Lata”, ”22”, ”45”] [”Anil”, ”21”, ”56”] [”John”, ”20”, ”60”] The reader object is an iterator. Hence, it supports next() function which can also be used to display all lines in csv file instead of a for loop. csvfile=open(”persons.csv”,”r”, newline=””) obj=csv.reader(csvfile) while True: try: row=next(obj) print (row) except StopIteration: break As mentioned earlier, csv module uses Excel as its default dialect. The csv module also defines a dialect class. Dialect is set of standards used to implement CSV protocol. The list of dialects available can be obtained by list_dialects() function. >>> csv.list_dialects() [”excel”, ”excel-tab”, ”unix”] In addition to iterables, csv module can export a dictionary object to CSV file and read it to populate Python dictionary object. For this purpose, this module defines following classes − DictWriter() This function returns a DictWriter object. It is similar to writer object, but the rows are mapped to dictionary object. The function needs a file object with write permission and a list of keys used in dictionary as fieldnames parameter. This is used to write first line in the file as header. writeheader() This method writes list of keys in dictionary as a comma separated line as first line in the file. In following example, a list of dictionary items is defined. Each item in the list is a dictionary. Using writrows() method, they are written to file in comma separated manner. persons=[ {”name”:”Lata”, ”age”:22, ”marks”:45}, {”name”:”Anil”, ”age”:21, ”marks”:56}, {”name”:”John”, ”age”:20, ”marks”:60} ] csvfile=open(”persons.csv”,”w”, newline=””) fields=list(persons[0].keys()) obj=csv.DictWriter(csvfile, fieldnames=fields) obj.writeheader() obj.writerows(persons) csvfile.close() The persons.csv file shows following contents − name,age,marks Lata,22,45 Anil,21,56 John,20,60 DictReader() This function returns a DictReader object from the underlying CSV file. As, in case of, reader object, this one is also an iterator, using which contents of the file are retrieved. csvfile=open(”persons.csv”,”r”, newline=””) obj=csv.DictReader(csvfile) The class provides fieldnames attribute, returning the dictionary keys used as header of file. print (obj.fieldnames) [”name”, ”age”, ”marks”] Use loop over the DictReader object to fetch individual dictionary objects. for row in obj: print (row) This results in following output − OrderedDict([(”name”, ”Lata”), (”age”, ”22”), (”marks”, ”45”)]) OrderedDict([(”name”, ”Anil”), (”age”, ”21”), (”marks”, ”56”)]) OrderedDict([(”name”, ”John”), (”age”, ”20”), (”marks”, ”60”)]) To convert OrderedDict object to normal dictionary, we have to first import OrderedDict from collections module. from collections import OrderedDict r=OrderedDict([(”name”, ”Lata”), (”age”, ”22”), (”marks”, ”45”)]) dict(r) {”name”: ”Lata”, ”age”: ”22”, ”marks”: ”45”} Print Page Previous Next Advertisements ”;