Book Image

Python Fundamentals

By : Ryan Marvin, Mark Nganga, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Nganga, Amos Omondi

Overview of this book

After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation. By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.
Table of Contents (12 chapters)
Python Fundamentals
Preface

Ordered Dictionaries


So far, the dictionaries that we have created do not maintain the insertion order of the key-value pairs that are added. Ordered dictionaries are dictionaries that maintain the insertion order of keys. This means that when you are iterating through them, you will always access the keys in the order in which they were inserted.

The OrderedDict class is a dict subclass defined in the collections package that Python ships with. We will use ordered dictionaries when it is vitally important to store and retrieve data in a predictable order; for example, when reading database entries.

The following section will describe how to work with them.

Creating an ordered dictionary is as easy as creating an instance of the OrderedDict class and passing in key-value pairs:

>>> from collections import OrderedDict
>>> a = OrderedDict(name="Zeus", role="god")
>>> a
OrderedDict([('name', 'Zeus'), ('role', 'god')])

Everything about OrderedDict, except for it maintaining...