Data Types in Python

Data Types in Python
Hostman Team
Technical writer
Python
06.12.2023
Reading time: 7 min

Python is a fully object-oriented programming language. Hence, all data in it is objects, which can be embedded at the language level or declared manually. 

Objects are instances of a class and the basic building blocks of any program, which are allocated memory to store data in them. So, for example, when we write x = 5 in code, we create an instance of the int class with the value 5 and assign it to the variable x. Now x is an object of the int type.

All objects have unique data types (int, string, list, etc.) and are created using the constructors of their respective classes. Classes, in turn, are mechanisms that define the behavior of objects thanks to unique attributes and methods. 

In this article, we will look at what data types there are in Python and talk about the features of each of them.

Variables

Variables in Python are named memory locations that store a variety of values within a Python program.

Each variable has its own data type, which tells the interpreter what can be stored in the variable and how much memory should be allocated for it.

The declaration of a variable is as follows:

x = 10

First of all, we specify the name of the variable, then we put an equal sign, and after that, we pass the value that will be assigned to the specified variable.

Each variable has its own location in memory. You can determine it using the id() function:

x = 10
print(id(x))

For the variable x from the example above, the location will be like this:

168d493b 3b23 4359 9edc 902cb8ba881a

There is also a type() function in Python, that allows us to find out the data type selected for a particular variable:

x = 10
print(type(x))

As you can see from the image below, an integer data type has been defined for x.

Ec3965d6 B426 48ba B32a E06d6bad2d82

The process of declaring a data type is called typing. It can be static or dynamic. Python uses the latter. That's why when the same variable is used, it can represent objects of completely different data types. For example:

first_example = 'Hello'
print(type(first_example))

first_example = 100
print(type(first_example))

first_example = 3.14
print(type(first_example))

In all cases of calling print, we will see a different result. 

Built-in data types

In this section, we will look at all the basic data types in the Python programming language. They can be divided into two groups: immutable and mutable objects.

You cannot change (mutate) the data in the immutable objects. You can only create a new object with the specified value and the same name. Immutable objects are objects of the numeric, string or tuple type.

Mutable objects, in turn, can be changed. This group includes objects of the list, dictionary or set types.

To check if the object is mutable, let's use the id() function and compare the memory locations before and after changes were made:

first_example = 50
second_example = [50, 100, 150]
print(f'Memory location before changing int object = {first_example} : {id(first_example)}')
print(f'Memory location before changing list object = {second_example} : {id(second_example)}')
first_example += 50
second_example += [200]
print(f'Memory location after changing int object = {first_example} : {id(first_example)}'')
print(f'Memory location after changing list object = {second_example} : {id(second_example)}')

You can see that when performing the addition operation with a variable of int type, a new object is created, the name of which is saved, but the value of the memory location is not. When adding a new value to an object of the list type, the address in memory does not change, which confirms its mutability.

You should take into account the mutability when working with functions. When you call a function with a mutable object as an argument, the function may perform mutations on that object, which will affect the original object. It is generally better to avoid mutating arguments inside your functions.

Numeric and boolean

First of all, let's look at the numeric data type in Python. 

Below is a table containing the name and description of the numeric data type, along with its notation and examples. We also added the boolean data type here.

Data type

Description

Example

Whole numbers (int)

Positive and negative numbers without decimals.

example1 = 5

example2 = -1234

Floating point numbers (float)

Positive and negative numbers with decimals

example3 = 3.14

example4 = -43.4132

Complex numbers (complex)

Numbers in the format: a + bj

where a and b are real numbers and j is an imaginary unit.

Complex numbers are passed using the complex() function.

The syntax for displaying the real part:

variable_name.real

The syntax for displaying the imaginary part:

variable_name.imag

example5 = complex(5,4)

Boolean (bool)

The boolean data type takes only 2 values: True and False

It is often used to implement branching or checkboxes.

example7 = True

example8 = False

Strings

The string data type stores text information or a sequence of bytes. To declare a string, you need to use single, double or triple quotes, as shown in the example below:

example_srt1 = ‘Example string #1’
example_srt2 = “Example string #2”
example_srt3 = '''Example string #3'''

As we said before, strings are immutable objects.

Lists

List in Python is an ordered collection of items. These items can be of different data types. Lists are mutable, meaning you can add, remove, and modify elements in a list.

You can create a list by using square brackets with elements between them, separated by commas, as shown in the example below:

example_list = [1, 5.7, 'hello']

To retrieve elements from a list, use indices. You can retrieve a single element or a slice. Example:

example_list = [1, 5.7, 'hello']
print(f'Third element of the list: {example_list[2]}')
print(f'First and second element of the list: {example_list[0:2]}')

Tuples

Tuples in Python are similar to lists but immutable. Their advantage is that the interpreter works with them much faster. So, if you want your program to run faster and your data to remain immutable, use tuples.

To create a tuple, we need to put comma-separated elements inside parentheses, as shown in the example below:

example_tuple = (1, 5.7, 'hello')

As to retrieving elements, we can do it using indices, just like lists. Just remember that you cannot mutate them.

Dictionaries

Dictionaries are an unordered list of key-value pairs. They provide quick access to data by using the appropriate key.

To declare a dictionary, list the data in a key-value format in curly braces, as shown in the example below:

example_dict = {
    'name':'Peter',
    'age':33,
    'country':'Netherlands'
}

It's important to remember that values can be of any data type, and keys are only immutable.

To get a value, use the corresponding key:

example_dict = {
    'name':'Peter',
    'age':33,
    'country':'Netherlands'
}

print(f'Peter is from: {example_dict["country"]}')
print(f'His age is: {example_dict["age"]}')

Sets

A set is a collection of unique immutable elements.

To declare a set, you must list the elements separated by commas in curly braces, as shown in the example below:

example_set = {1,2,3,4,5}

If we try to pass duplicate elements into a set, the interpreter will automatically remove them. 

example_set = {1,2,3,4,5,1,2,3,4,5}
print(example_set)

As a result, the print(example_set) function will print the following:

F7c75f0d 64a6 4547 8034 23aa9f277a5d

Another feature of sets is that we can perform a number of mathematical operations (union, difference, intersection) on them.

What to remember

  • All objects have their own unique data types (int, string, list, etc.) and are created using the constructors of the corresponding classes.

  • Variables in Python are named memory locations that store values. Each variable has its own data type, which tells the interpreter what can be stored in that variable and how much memory should be allocated to it.

  • You cannot change the state and contents of immutable objects. Instead, you can create a new object with the specified value and the same name. Immutable objects are of the number, string or tuple types.

  • Mutable objects can be changed. This group includes the list, dictionary, and set types.

  • The numeric data type includes integers, floating point numbers, and complex numbers.

  • The boolean data type takes only two values: True or False.

  • The string data type stores text information or a sequence of bytes.

  • Lists are ordered collections of items that can be of different data types.

  • Tuples in Python are the same as lists, but immutable.

  • A dictionary is an unordered list of key-value pairs.

  • A set is a collection of unique and unordered elements of an immutable type.

Python
06.12.2023
Reading time: 7 min

Similar

Python

Dictionaries in Python

A dictionary (or dict) is an unordered data structure in Python (unlike a list) that takes the form of "key-value" pairs. In simpler terms, a dictionary is like a notebook with no specific order, where each number (value) is associated with a specific name (key). James +357 99 056 050 Julia +357 96 540 432 Alexander +357 96 830 726 Each key in a Python dictionary is completely unique, but the values can be repeated. For example, if you add a new entry with the name "Julia" (value) and a new number (key), the entry will not duplicate but instead update the existing value. To find a specific number, you need to provide the name. This makes Python dictionaries a convenient way to search through large datasets. The following data types can be used as keys: Strings Numbers (integers and floats) Tuples Values can be any data type, including other dictionaries and lists. Creating a Dictionary This guide uses Python version 3.10.12. Using Curly Braces {} The simplest and most straightforward way to create a dictionary is by using curly braces. For example, this creates an empty dictionary with no keys or values: empty_dictionary = {} Here’s how to create a dictionary with keys and values inside: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} The names in quotes are the keys, and the numbers are their values. The previously shown table can be represented as a dictionary like this: team_phones = { "James": "+357 99 056 050", "Julia": "+357 96 540 432", "Alexander": "+357 96 830 726" } In this case, the values are of string type, not numeric. By the way, you can also use single quotes instead of double quotes: team_phones = { 'James': '+357 99 056 050', 'Julia': '+357 96 540 432', 'Alexander': '+357 96 830 726' } Using the dict() Function As with many other types of variables, a dictionary can be created using its corresponding function. For example, this creates an empty dictionary: just_dictionary = dict() And this creates a dictionary with keys and values: keys_and_values = [("Alexander", 23), ("Victoria", 43), ("Eugene", 26), ("Meredith", 52), ("Maria", 32)] team_ages = dict(keys_and_values) In this case, a list of so-called tuples — pairs of "key-value" — is created first. However, there is a more concise way to create a dictionary using the function: team_ages = dict(Alexander = 23, Victoria = 43, Eugene = 26, Meredith = 52, Maria = 32) Here, each function argument becomes a key with a corresponding value in the new dictionary. Using the dict.fromkeys() Function Another way to create a dictionary is by converting a list into a dictionary. There are a few nuances to this approach: The elements of the list become the keys of the new dictionary. You can specify a default value for all keys at once, rather than for each key individually. For example, this creates a dictionary where the values of the keys will be empty: team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"] # list with keys team_ages = dict.fromkeys(team_names) print(team_ages) The console output will be: {'Alexander': None, 'Victoria': None, 'Eugene': None, 'Meredith': None, 'Maria': None} And this creates a dictionary with a specified value, which will be common for all keys: team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"] team_ages = dict.fromkeys(team_names, 0) # setting the default value as the second argument print(team_ages) The console output will be: {'Alexander': 0, 'Victoria': 0, 'Eugene': 0, 'Meredith': 0, 'Maria': 0} Dictionary Comprehension A more unconventional way to create a dictionary is by generating it from other data using a so-called dictionary comprehension, which is a compact for loop with rules for dictionary generation written inside. In this case, the generator loop iterates through the data structure from which the dictionary is created. For example, here’s how to create a dictionary from a list with a default value for all keys: team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"] team_ages = {name: 0 for name in team_names} # dictionary generator with 0 as the default value print(team_ages) The console output will be identical to the previous example: {'Alexander': 0, 'Victoria': 0, 'Eugene': 0, 'Meredith': 0, 'Maria': 0} However, the main advantage of this method is the ability to assign individual values to each key. For this, you need to prepare two lists and slightly modify the basic dictionary comprehension syntax: team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"] team_numbers = [23, 43, 26, 52, 32] team_ages = {name: age for name, age in zip(team_names, team_numbers)} # using the zip() function to iterate over two lists simultaneously print(team_ages) The zip() function combines the two lists into a list of tuples, which is then iterated over in the comprehension loop. In this case, the console output will be: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} There is also a more complex variant that generates a dictionary from a single list containing both keys and values: team_data = ["Alexander", 23, "Victoria", 43, "Eugene", 26, "Meredith", 52, "Maria", 32] # keys and values are stored sequentially in one list team_ages = {team_data[i]: team_data[i+1] for i in range(0, len(team_data), 2)} # loop runs through the list with a step of 2 print(team_ages) In this example, the range() function sets the length and iteration step for the loop. The console output will be identical to the previous ones: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} Adding Elements You can add an element to a dictionary by specifying a previously non-existent key in square brackets and assigning a new value to it: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_ages["Catherine"] = 28 # Adding a new key-value pair print(team_ages) The console output will be: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'Catherine': 28} Modifying Elements Modifying an element is syntactically the same as adding one, except that the element already exists in the dictionary: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_ages["Victoria"] = 44 # Updating the existing value print(team_ages) The console output will be: {'Alexander': 23, 'Victoria': 44, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} Accessing Elements You can access the values in a dictionary using square brackets with the key: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} print(team_ages["Eugene"]) The console output will be: 26 Or with a more visual example using the previously shown table: team_phones = { "James": "+357 99 056 050", "Julia": "+357 96 540 432", "Alexander": "+357 96 830 726" } print(team_phones["Julia"]) The console output will be: +357 96 540 432 Removing Elements You can remove an element from a dictionary using the del keyword: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} del team_ages["Victoria"] # Deleting the element with the key "Victoria" print(team_ages) The console output will not contain the deleted element: {'Alexander': 23, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} Managing Elements A dictionary in Python has a set of special methods for managing its elements — both keys and values. Many of these methods duplicate the previously shown functions for adding, modifying, and deleting elements. The dict.update() Function This method adds new elements to a dictionary by passing another dictionary as an argument: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_ages.update({ "John": 32, "Catherine": 28 }) print(team_ages) The output in the console will be: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'John': 32, 'Catherine': 28} The same result can be achieved by pre-creating a dictionary with the elements to be added: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_add = {"John": 32, "Catherine": 28} team_ages.update(team_add) print(team_ages) Again, the output will be the same: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'John': 32, 'Catherine': 28} The dict.get() Function You can access the value of a dictionary not only with square brackets but also through the corresponding function: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} print(team_ages.get("Victoria")) print(team_ages["Victoria"]) Both console outputs will be: 4343 Now, what happens if a non-existing key is passed as an argument: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} print(team_ages.get("Anastasia")) The console output will be: None However, the main feature of get() compared to square brackets is the ability to specify a value for a non-existing key as the second argument: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} print(team_ages.get("Anastasia", "Non-existent employee")) In this case, the console output will be: Non-existent employee When using square brackets, you would need to use a try/except block to handle cases where you are not sure if the key exists. The dict.pop() Function In dictionaries, there is a specific function to delete an element by key: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_ages.pop("Alexander") print(team_ages) The console output will be: {'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} The dict.popitem() Function Instead of deleting a specific element by key, you can delete the last added item: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_add = {"John": 32, "Catherine": 28} team_ages.update({"John": 32}) print(team_ages) team_ages.popitem() print(team_ages) The console output will show the dictionary with the added element and then its contents after the element is removed: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'John': 32} {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} The dict.clear() Function You can completely clear a dictionary using the corresponding method: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_ages.clear() print(team_ages) The console output will show an empty dictionary: {} The dict.copy() Function You can fully copy a dictionary: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} team_ages_copy = team_ages.copy() print(team_ages) print(team_ages_copy) The console output will contain the same content from two different dictionaries: {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} {'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32} The dict.setdefault() Function Sometimes, the mechanics of adding or retrieving a key are not enough. Often, you need more complex behavior. For example, in some cases, you need to check for the presence of a key and immediately get its value, and if the key doesn't exist, it should be automatically added. Python provides a special method for this operation: team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32} print(team_ages.setdefault("Alexander")) # This key already exists print(team_ages.setdefault("John")) # This key doesn't exist, so it will be created with the value None print(team_ages.setdefault("Catherine", 29)) # This key doesn't exist, so it will be created with the value 29 The console output will show results for all requested names, regardless of whether they existed at the time of the function call: 23None29 Dictionary Transformation You can extract data from a dictionary's keys and values. Typically, this extraction operation is performed to convert the dictionary into another data type, such as a list. There are several functions for extracting data from a dictionary in Python: dict.keys() — returns an object with the dictionary's keys dict.values() — returns an object with the dictionary's values dict.items() — returns an object with "key-value" tuples Here's an example of how to extract data from a dictionary and convert it into a list: team_phones = { "James": "+357 99 056 050", "Julia": "+357 96 540 432", "Alexander": "+357 96 830 726" } # All returned objects are converted into lists using the list() function team_names = list(team_phones.keys()) # List of dictionary keys team_numbers = list(team_phones.values()) # List of dictionary values team_all = list(team_phones.items()) # List of "key-value" pairs print(team_names) print(team_numbers) print(team_all) The console output will be: ['James', 'Julia', 'Alexander'] ['+357 99 056 050', '+357 96 540 432', '+357 96 830 726'] [('James', '+357 99 056 050'), ('Julia', '+357 96 540 432'), ('Alexander', '+357 96 830 726')] In the above example, the returned objects from the dictionary are explicitly converted into lists. However, this step is not necessary: team_phones = { "James": "+357 99 056 050", "Julia": "+357 96 540 432", "Alexander": "+357 96 830 726" } print(team_phones.keys()) print(team_phones.values()) print(team_phones.items()) The console output will be: dict_keys(['James', 'Julia', 'Alexander']) dict_values(['+357 99 056 050', '+357 96 540 432', '+357 96 830 726']) dict_items([('James', '+357 99 056 050'), ('Julia', '+357 96 540 432'), ('Alexander', '+357 96 830 726')]) Conclusion In Python, a dictionary is an unordered data structure in the form of "key-value" pairs, with which you can perform the following operations: Creating a dictionary from scratch Generating a dictionary from other data Adding elements Modifying elements Accessing elements Removing elements Managing elements Transforming the dictionary Thus, a dictionary solves many problems related to finding a specific value within a large data structure — any value from the dictionary is retrieved using its corresponding key. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
10 January 2025 · 12 min to read
Python

How to Remove Spaces from a String in Python

Strings are one of the fundamental data types in Python, storing a sequence of characters. With strings, you can perform many operations: splitting, joining, replacing, comparing, and more. Sometimes, it's necessary to format strings by removing unnecessary characters, such as spaces. This article will cover the methods available in Python (version 3.10.12) for removing spaces from strings. Removing Spaces from the Start and End Often, we need to remove only extra spaces, such as those at the start or end of a string. Python provides several similar methods for this purpose: strip() removes spaces from both the string's start and end. lstrip() removes spaces only from the start. rstrip() removes spaces only from the end. Here’s an example of how to clean up a string by removing spaces at the edges: text_before = " This is a string with spaces " text_after = text_before.strip() text_after_left = text_before.lstrip() text_after_right = text_before.rstrip() print(text_after) print(text_after_left) print(text_after_right) Console output: This is a string with spaces This is a string with spaces This is a string with spaces Removing All Spaces In some cases, you may need to remove all spaces entirely. This can be done by replacing every space character with an empty string: text_before = " This is a string with spaces " text_after = text_before.replace(' ', '') print(text_after) Console output: Thisisastringwithspaces Another way to remove all spaces is to use the translate() method. While less intuitive, it can be more flexible in certain scenarios: text_before = " This is a string with spaces " text_after = text_before.translate({ord(' '): None}) print(text_after) Console output: Thisisastringwithspaces The translate() function takes a dictionary as an argument, where the keys are ASCII codes of characters to be replaced, and the values are the replacement characters. The ord() function converts a character to its corresponding ASCII code. With translate(), you can replace multiple characters at once. For example: text_before1 = " This is a string with spaces " text_before2 = " 1 2 3 4 5 " text_before3 = " { 'someData': 100, 'otherData': 'information' } " space_table = str.maketrans({' ': None}) text_after1 = text_before1.translate(space_table) text_after2 = text_before2.translate(space_table) text_after3 = text_before3.translate(space_table) print(text_after1) print(text_after2) print(text_after3) Console output: Thisisastringwithspaces 12345 {'someData':100,'otherData':'information'} Removing Repeated Spaces The simplest way to remove all repeated spaces in a string is to perform the following steps: Split the string using the split() function by spaces as delimiters, resulting in a list of substrings. Join the substrings from the list back into a single string using the join() function with a single space as the separator. Here’s how this can be done: text_before = " This is a string with spaces " # Split the string into substrings; spaces are the default delimiter text_splitted = text_before.split() # Join the substrings into a single string using a space as the delimiter text_after = ' '.join(text_splitted) print(text_after) In the console, you’ll see the formatted string without extra spaces: This is a string with spaces You can write the same operations more concisely: text_before = " This is a string with spaces " text_after = ' '.join(text_before.split()) print(text_after) The console output will remain the same: This is a string with spaces Using this method, you can also replace spaces with any other character: text_before = " This is a string with spaces " text_after = '_'.join(text_before.split()) print(text_after) In this case, the console output will be: This_is_a_string_with_spaces Removing Spaces Using Regular Expressions The methods shown earlier are effective for simple scenarios. However, strings often have more complex patterns, requiring advanced methods to remove spaces. A highly flexible way to handle string modifications is by using regular expressions. Here’s an example: import re # Import the module for working with regular expressions # A string containing sequences of two or more spaces, as well as some single spaces text_before = " This is a string with spaces . " # Replace all sequences of two or more spaces with a single space text_after = re.sub(r"\s+", " ", text_before) print(text_after) The console output will be a string where only single spaces remain: This is a string with spaces . This example introduces some problems: Multiple spaces before the period at the end are replaced with a single space. However, there should not be any space before the period. A sequence of spaces at the start of the string is replaced by a single space. However, there should not be any spaces at the beginning of the string. We can resolve these issues by applying a sequence of transformations: import re text_before = " This is a string with spaces . " # Remove spaces at the start and end of the string using the OR operator (|) text_after = re.sub(r"^\s*|\s*$", "", text_before) # Replace all repeated spaces with a single space text_after = re.sub(r"\s+", " ", text_after) # Replace all periods surrounded by spaces with just a period text_after = re.sub(r"\s*[.]\s*", ".", text_after) print(text_after) The console output will now contain a properly formatted string without unnecessary spaces: This is a string with spaces. Here: \s: Matches any whitespace character (spaces, tabs, etc.). +: Matches one or more repetitions of the preceding element. *: Matches zero or more repetitions of the preceding element. |: Represents a logical OR, allowing you to combine multiple conditions. ^: Anchors the match at the beginning of the string. $: Anchors the match at the end of the string. When using regular expressions, it’s important to understand the potential structure of the strings being processed to design an appropriate solution. For example: If the string may have periods surrounded by spaces, this must be handled explicitly. The more complex the string patterns, the more intricate the logic for removing spaces becomes. Ultimately, removing spaces from a string in Python often requires a custom solution tailored to the specific case. Removing Spaces Using a Loop For more complex string manipulation (in this case, removing spaces), you can manually check each character in a loop with multiple conditions. This approach offers more flexibility and control over the process. In the simplest case, removing spaces inside a loop looks like this: # Define a function for more complex string processing logic def complexRemoval(string): after = "" for i in string: if not i.isspace(): # The isspace() function checks if the character is a space and returns a boolean result (True or False) after += i return after text_before = " This is a string with spaces . " text_after = complexRemoval(text_before) print(text_after) The console output will contain all the characters of the original string, but without spaces: Thisisastringwithspaces. Clearly, this isn't the desired result, so we need to complicate the logic for removal. To refine the logic, we can introduce a variable to track whether the previous character was a space: def complexRemoval(string): after = "" wasSpace = True # Variable to track if the previous character was a space for i in string: if not i.isspace(): # If the character is not a space if i == '.' and wasSpace: # If we encounter a period and the previous character was a space, remove it after = after[:len(after) - 1] # Remove the last character (space) after += i wasSpace = False elif not wasSpace: # If it's a space but the previous character was not a space after += i wasSpace = True return after # Test cases print(complexRemoval(" This is a string with spaces . ")) print(complexRemoval("Lots of different spaces blah blah blah . Also a period . ")) The output in the console will now show perfectly formatted strings without unnecessary spaces: This is a string with spaces.Lots of different spaces blah blah blah. Also a period. This method allows for more complex processing of spaces in strings, such as removing spaces before periods or handling sequences of spaces efficiently. Conclusion The Python programming language offers a specific set of built-in tools for string manipulation — for example, operations with space characters: Removing spaces at the beginning of a string Removing spaces at the end of a string Removing spaces from both ends of a string Removing all spaces in a string Removing spaces from a string according to specific rules (using regular expressions) Removing spaces according to unique rules (using iteration) Each variant has its own set of methods — most of which we have covered in this guide. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
10 January 2025 · 8 min to read
Python

How to Check if a Key Exists in a Python Dictionary

A dictionary (dict) in Python is an unordered data structure that uses a "key-value" format. Any value within the dictionary is accessed by explicitly referencing the key associated with the desired value. Attempting to access a non-existent key results in a program error. To avoid such errors, it’s essential to check whether a key exists in a dictionary before trying to access its value. Python provides several built-in methods for this purpose, which we discuss in this tutorial. In this guide, we use Python 3.10.12 running on Ubuntu 22.04. Using the in Operator with a Dictionary The most common way to check if a key exists in a dictionary is by using the in operator in an if/else condition: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'name' if some_key in some_dict: print('The key "' + some_key + '" was found.') else: print('The key "' + some_key + '" was not found.') Here, the in operator returns True if the key is found and False otherwise. Using the in Operator with dict.keys() You can also use the in operator with the list of dictionary keys obtained via the dict.keys() method: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'name' if some_key in some_dict.keys(): print('The key "' + some_key + '" was found.') else: print('The key "' + some_key + '" was not found.') As you can see, the logic is identical to the previous example, except that the dict.keys() method is used instead of the dictionary instance. At first glance, this approach might seem redundant. However, in practical applications, there may be scenarios where you specifically need to work with the list of dictionary keys rather than the dictionary itself. Using dict.keys(), you can elegantly determine if a specified key exists in the dictionary. Using the dict.get() Function You can check for the presence of a key in a dictionary by attempting to retrieve its value using the built-in dict.get() method: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'salary' some_value = some_dict.get(some_key) # Try to fetch the value for the key # If the returned value is None, it indicates the key does not exist if some_value is not None: print('The key "' + some_key + '" was found, and its value is "' + str(some_value) + '".') else: print('The key "' + some_key + '" was not found.') As shown, accessing a non-existent key with dict.get() will not raise an error (as would happen with square bracket access) but will return a None value. However, this method has a potential drawback: the requested key might actually exist in the dictionary, but its value could still be None: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...', 'salary': None} some_key = 'salary' # The key exists, but its value is None some_value = some_dict.get(some_key) # Returns None print('It is unclear if the key "' + some_key + '" exists or if it exists with a value of None.') In such cases, whether the key does not exist or exists with a None value is ambiguous. We can address this issue by using the ability of dict.get() to set a default value for non-existent keys: some_dict1 = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...', 'salary': None} some_dict2 = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'salary' some_value1 = some_dict1.get(some_key, "Salary not specified") some_value2 = some_dict2.get(some_key, "Salary not specified") print('Attempting to access the key "' + some_key + '" returned the value "' + str(some_value1) + '".') print('Attempting to access the key "' + some_key + '" returned the value "' + str(some_value2) + '".') Console output: Attempting to access the key "salary" returned the value "None". Attempting to access the key "salary" returned the value "Salary not specified". If you attempt to retrieve the value of a non-existent key using square brackets, it will always result in an error. In the future, this error can be handled using a try/except block, thereby determining whether the key actually exists. try/except Exception Handling You can check if a key exists in a dictionary by handling errors with try/except—a direct, "straightforward" approach. In this method, if accessing the key raises an error, it indicates that the key does not exist. Conversely, if no error is raised, the key exists. To implement this, wrap the key access in a try/except block: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'name' try: some_value = some_dict[some_key] print('The key "' + some_key + '" was found, and its value is "' + some_value + '".') except KeyError: print('The key "' + some_key + '" was not found.') This method of checking for a key in a Python dictionary should generally be used as a fallback when other methods are not suitable. This is because exception handling in Python tends to be relatively slow, which can reduce program performance. Nonetheless, checking a key via try/except is a valid approach when needed. Using a for Loop In programs with more complex logic, explicit key searches in a dictionary might be required—especially if the search is combined with modifying the values of the found keys. In such cases, you can manually iterate over the dictionary using a for loop: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'name' is_found = False # Variable to store the search status # Iterate through the dictionary for found_key in some_dict: if found_key == some_key: is_found = True some_dict[found_key] = 'Jim' # Modify the value of the found key if is_found: print('The key "' + some_key + '" was found, and its value is now "' + some_dict[some_key] + '".') else: print('The key "' + some_key + '" was not found.') In this example, all dictionary keys are sequentially iterated over, and the value of the found key is modified. This approach allows for implementing more complex logic, combining both key searches and value modifications. Using a while Loop In some cases, it might be useful to use a while loop instead of a for loop: some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'} some_key = 'occupation' is_found = False some_keys = list(some_dict) # Convert dictionary keys to a list i = 0 while i < len(some_keys): if some_keys[i] == some_key: is_found = True some_dict[some_key] = 'Jim' # Modify the value of the found key break i += 1 if is_found: print('The key "' + some_key + '" was found, and its value is now "' + some_dict[some_key] + '".') else: print('The key "' + some_key + '" was not found.') While the overall application logic does not change, the syntax differs from the for loop approach. Conclusion Before accessing a value in a dictionary, it is essential to ensure that the desired key exists in the dictionary. Otherwise, you may encounter an error, causing the program to crash. This check can be performed using several built-in methods: in operator dict.get() function try/except exception handling for and while loops Each specific scenario calls for a different method of checking. For the simplest cases, the in operator is typically used. When the application logic is more complex and requires additional actions, a for or while loop may be employed. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
09 January 2025 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support