DEV Community

loading...
Cover image for Python: Modules, Dictionaries, Tuples & Classes 🌟

Python: Modules, Dictionaries, Tuples & Classes 🌟

killianfrappartdev profile image Killian Frappart ・4 min read

This is my second week of Python and the second episode of this Python dedicated series 🤓

I am a big fan of "organization" and today I decided to learn more about related topics.

As always, please keep in mind that I am writing and learning simultaneously. Therefore, you might come across mistakes while reading through this article even if I double-check every topic I write about.

Table of Contents

Packages & Modules

Set up a new project and install dependencies was not that intuitive for me, so I will walk with you through the main steps.

Create an environment

The idea here is to create a context for your project. Imagine that you have an open source project with many contributors, how tedious would it be to tell everybody how to set up and configure locally ?

You want to make sure that every contributor is running the project in the same environment and can easily install dependencies.

Python3 is shipped with the venv package which gives you the possibility to create a virtual environment like this:

$ python3 -m venv <environment-name>

Install packages

Nobody wants you to write code that has been written before, there is a huge community of developers that offers you an incredible amount of packages.

A package is a container for one or more modules and a module is simply a python file that exports variables, classes or functions.

If you are familiar with JavaScript, you probably know NPM or Yarn. PyPi is the most common option to install packages in your Python project.

$ pip install <package-name>

You should always have a file in your project that list all packages installed.

$pip freeze > requirements.txt

Import modules

As I said, a module is nothing more than a python file that lets you access its content.

Here is an example:

# hello.py

def greeting():
  print("Hello")

# main.py

import hello

hello.greeting()
Enter fullscreen mode Exit fullscreen mode

It is as simple as that 🤯 Optionally, you can rename your imports as follows:

# main.py

import hello as hi

hi.greeting()
Enter fullscreen mode Exit fullscreen mode

Lastly, it is also possible to import some specific functions or variables from a module like this:

# main.py

from hello import greeting

greeting()
Enter fullscreen mode Exit fullscreen mode

Dictionaries

In my last article, I introduced lists which is a really useful data structure.

Lists work just fine, but it might not be the solution for every problem you face.

Today, I would like to write about dictionaries. A dictionary is a data structure that store data as key-value pairs.

Dictionary item:
✅ Unordered
✅ Changeable
✅ Values can be any data type
❌ Duplicates not allowed

# Create a new dictionary
tech_dictionary = {
    "React": "Library for building user interfaces.",
    "Node": "JavaScript runtime.",
    "C#": "Strongly typed programming language",
}

# Read
print(tech_dictionary["Node"]) # "JavaScript runtime."

# Check if key exists
if "Java" in tech_dictionary:
  print(Java is in the dictionary!)

# Change item value
tech_dictionary["React"] = "Popular frontend library"

# Add item
tech_dictionary["Python"] = "Most famous programming language in 2020"

# Remove item
tech_dictionary.pop("C#")
Enter fullscreen mode Exit fullscreen mode

Tuples

Speaking of data structure, it is worth to mention tuples. A tuple is used to store a collection of data in a single variable.

Tuple item:
✅ Ordered
✅ Allow duplicates
❌ Unchangeable

# Create a new tuple
tech_tuple = ("C++", "Django", "Ruby")

# Read
print(tech_tuple[1]) # "Django"

# Convert a tuple to a list
tech_list = list(tech_tuple)

# Change item value
tech_tuple[1] = "Flask"

# Items cannot be added or removed after tuple is created
Enter fullscreen mode Exit fullscreen mode

Classes

Python is an object-oriented programming language. OOP is a though topic that I will not dive too deep in because of its complexity.

Still, I will introduce classes and related syntax. If you have never worked with classes before, it is a very common feature available in many programming languages.

A class is a blueprint used to build objects.

# Create a new class
class Car:

    # Constructor
    def __init__(self, color):

    # Attributes
    self.color = color

    # Methods
    def info(self):
        print(self.color)
Enter fullscreen mode Exit fullscreen mode

Constructor

Every class has an init function which is executed when a new instance of the class is created.

This function should be used to assign values or execute some operations.

The "self" parameter is used to access values of a given instance.

def __init__(self, color, weight):
   self.color = color
   self.weight = weight
   print("New car created")
Enter fullscreen mode Exit fullscreen mode

Attributes

Attributes are variables related to an instance of a class. They can be modified from the outside.

car = Car("Red", 200)
print(car.color) # "Red"

car.weight = 500
print(car.weight) # 500
Enter fullscreen mode Exit fullscreen mode

Methods

Methods are functions that belongs to a class instance.

red_car = Car("Red")
blue_car = Car("Blue")

red_car.info() # "Red"
blue_car.info() # "Blue"
Enter fullscreen mode Exit fullscreen mode

Thank you for reading 😇

Discussion (0)

pic
Editor guide