Loops in Python 3

Loops in Python 3
Hostman Team
Technical writer
Python
06.12.2023
Reading time: 8 min

You're probably already familiar with the if statement and the if-else and if-elif-else constructs. Now let's learn about loops. In this article, we will look at the simplest for and while loops, statements for interrupting and continuing them (break and continue, respectively), and examples of using if-elif-else statements to create additional conditions.

Loops in Python 3 and why you need them

Cyclic tasks are an integral part of our lives. Take shopping for groceries with a list. We look at the list, look for the desired product and put it in the cart, then go to the second item and repeat the same operation until the end of the list, after which we exit the program discard the list and move on to the next part of the code task. After the last item is executed, the list is discarded. Loops work in programming in the same way: the program will continue executing a certain piece of code as long as some condition specified for this piece or, as programmers say, for the loop body, is met.

The conditions are set with the special operators while or for, and a single execution of the loop body is called an iteration. There can be as many iterations as you want and they will be executed as long as the condition is true. If you make a logical mistake when writing the code, the iterations risk becoming infinite. In such cases, we speak of infinite loops, which, however, can be called intentionally.

For Loop in Python

The for statement is needed to loop through a known number of values in a list. for is one of the main helpers of a Python programmer; it saves a lot of time since you don't have to retype the same code many times. But enough theory, let's write some code to make it clearer what for does:

word = "hostman"
for letter in word:
   print (letter)

We get this result:

h
o
s
t
m
a
n

The program searches through all elements, in this case the characters that make up the string, and outputs them as a sequence. But they can also be elements of a list. A list is created using [] symbols, and its elements are enumerated using commas. For example, let's take our shopping list and display it on the screen:

products = ['milk', 'bread', 'eggs', 'sausage', 'sugar', 'flour']
for element in products:
   print (element)
milk
bread
eggs
sausage
sugar
flour

Now, a few remarks for beginners:

  • Do not forget the indentation in the loop body after the main lines with for and while operators.

  • You can use single or double quotes to correctly label strings and elements (in the examples above, we used both types), but in practice, it's better to use one of them so as not to worsen the code readability.

  • Programmers usually use variables i and j to denote counters, but it's possible to label them differently. In these examples, for the sake of clarity, we have intentionally labeled counters as letter and element to make it clear which values they search for.

While Loop in Python

The function of the while statement is different. As long as the condition entered by while is true, the loop body will continue to execute, and the number of iterations is not known in advance (unlike loops with the for statement). Example:

number = 1
while number < 10:
    print (number)
    number += 2
print ('The next value is greater than 10, so the count stopped.')

Here is the result of executing the code:

1
3
5
7
9
The next value is greater than 10, so the count stopped.

One of the features of Python is that the language is as visual as possible, and it's often clear what work the code is doing without detailed explanations. In this case, we have the following: we assigned the value 1 to the number variable and created a condition—as long as the value is less than 10, the loop body will be executed. In the body, we have created two instructions, one visible (to display the next value on the screen) and the other one adds the specified number to the variable value and overwrites this value. We could rewrite this line as follows:

number = number + 2

The entries x = x + 2 and x += 2 are equivalent (Python allows you to use different code to do the same thing in some cases).

As soon as the condition introduced by the while statement is no longer true (the number becomes greater than 10), the loop body stops executing, and the program moves to the final line (note that it is on a different level, so it is not indented), and a message is displayed:

The next value is greater than 10, so the count stopped

Using if-elif-else statements on loops

Now let's consider more complex and functional examples of constructs with while, which are created using the if, elif, and else statements. 

x = 0
while x < 10:
    if x == 0:
        print (x, "if statement is true")
        x += 1
    elif x <= 5:
        print (x, "First elif statement is true")
        x += 1
    elif x > 5 and x < 9:
        print (x, "Second elif statement is true")
        x += 1
    else:
        print (x, "else statement is true")
        x += 1
print ("That’s the count.")

Here’s the result:

0 if statement is true
1 first elif statement is true

6 second elif statement is true

9 else statement is true
That’s the count.

After assigning the value 0 to the variable x, we create a condition for the while loop, and using the if, elif and else operators, we add a set of conditions that will cause a certain text to be displayed on the screen. The if condition triggers when x is 0, and the first elif triggers when x is less than or equal to 5. In the case of the second elif, we also used the and operator, which adds an extra condition so that the user also sees the text that is displayed when the else condition is met. Python checks the truth of conditions sequentially, so if any condition higher up on the list remains true until the last iteration, the directives for the conditions below will not be executed.

Break and Continue Statements

The break and continue statements provide additional ways to work with loops. Here's what they do:

  • break is used to interrupt a loop;

  • continue is used to skip a certain iteration and move on to the next one, but without terminating the loop.

For an example of how the break statement works, let's slightly modify the code from the previous chapter and try to execute it:

x = 0
while x < 10:
    if x == 0:
        print (x, "if statement is true")
        x += 1
    elif x <= 5:
        print (x, "first elif statement is true")
        x += 1
    elif x > 5 and x < 9:
        print (x, "second elif statement is true")
        x += 1
    else:
        print (x, "else statement is true")
print ("That’s the count.")

We removed the x += 1 line after the else operator and got into an infinite loop! Of course, we can just return the line, but we can also do it this way:

x = 0
while x < 10:

    else:
        print (x, "else statement is true")
        break
print ("That’s the count.")

Now, after adding the break statement, when the else condition is met, the loop will no longer be infinite, and the message will appear on the screen (That's the count).

Here is an example of how the continue statement works:

products = ['milk', 'bread', 'eggs', 'sausage', 'sugar', 'flour']
print ('Shopping list:')
print ()
for element in products:
    if element == 'sausage':
        continue
    print (element)
print ()
print ('And sausage is already bought.')

The result of the program:

Shopping list:
milk
bread
eggs
sugar
flour
And sausage is already bought.

As we can see, the sausage is no longer on the list: as soon as the program reaches it, the continue command comes into play, instructing it to ignore this item. But the loop is not interrupted, so the other products from the list are also displayed on the screen.

Nested Loops in Python

You can also use loop operators to create nested loops in Python 3. 

Example:

for i in range (1, 4):
    for j in range (1, 4):
        print (i * j, end=" ")
  print ()

The result of the program:

1 2 3
2 4 6
3 6 9

You have already guessed that this is the way to achieve consecutive multiplication of numbers (the i * j directive inside nested for loop is responsible for this, and the code end="" prints the obtained values with spaces). The last print() line, referring to the main for loop (this is implemented by indentation), is also necessary for clarity: in this case the program will print the obtained values in a column.

Beginners may also ask why there is no 4 8 12 line in the output? This is a peculiarity of the built-in range function that specifies the range of values: it does not include the last number, so for that line to appear, we should write the code like this:

for i in range (1, 5):
    for j in range (1, 4):
        print (i * j, end=" ")
  print ()
1 2 3 
2 4 6 
3 6 9
4 8 12 

Conclusion

In this short article, we got acquainted with for and while loops, learned how to use conditional if-elif-else constructs together with loops, and how to use break and continue statements. With a little practice, you will be able to write more complex code than presented in our examples. Good luck!

Check out our app platform to find a variety of Python applications, including Celery, Django, FastAPI and Flask. 

Python
06.12.2023
Reading time: 8 min

Similar

Python

How to Split a String Using the split() Method in Python

Working with strings is integral to many programming tasks, whether it involves processing user input, analyzing log files, or developing web applications. One of the fundamental tools that simplifies string manipulation in Python is the split() method. This method allows us to easily divide strings into parts based on specified criteria, making data processing and analysis more straightforward. In this article, we'll take a detailed look at the split() method, its syntax, and usage features. You'll learn how to use this method for solving everyday tasks and see how powerful it can be when applied correctly. Regardless of your programming experience level, you'll find practical tips and techniques to help you improve your string-handling skills in Python. What is the split() Method? The split() method is one of the core tools for working with strings in Python. It is designed to split a string into individual parts based on a specified delimiter, creating a list from these parts. This method is particularly useful for dividing text into words, extracting parameters from a string, or processing data separated by special characters, such as commas or tabs. The key idea behind the split() method is to transform a single string into a set of smaller, more manageable elements. This significantly simplifies data processing and allows programmers to perform analysis and transformation tasks more quickly and efficiently. Syntax of split() The split() method is part of Python's standard library and is applied directly to a string. Its basic syntax is as follows: str.split(sep=None, maxsplit=-1) Let’s break down the parameters of the split() method: sep (separator) This is an optional parameter that specifies the character or sequence of characters used as the delimiter for splitting the string. If sep is not provided or is set to None, the method defaults to splitting the string by whitespace (including spaces, tabs, and newline characters). If the string starts or ends with the delimiter, it is handled in a specific way. maxsplit This optional parameter defines the maximum number of splits to perform. By default, maxsplit is -1, which means there is no limit, and the string will be split completely. If maxsplit is set to a positive number, the method will split the string only the specified number of times, leaving the remaining part of the string as the last element in the resulting list. These parameters make it possible to customize split() to meet the specific requirements of your task. Let’s explore practical applications of split() with various examples to demonstrate its functionality and how it can be useful in daily data manipulation tasks. Examples of Using the split() Method To better understand how the split() method works, let's look at several practical examples that demonstrate its capabilities and applicability in various scenarios. Splitting a String by Spaces The most common use of the split() method is to break a string into words. By default, if no separator is specified, split() divides the string by whitespace characters. text = "Hello world from Python" words = text.split() print(words) Output: ['Hello', 'world', 'from', 'Python'] Splitting a String by a Specific Character If the data in the string is separated by another character, such as commas, you can specify that character as the sep argument. vegetable_list = "carrot,tomato,cucumber" vegetables = vegetable_list.split(',') print(vegetables) Output: ['carrot', 'tomato', 'cucumber'] Splitting a String a Specified Number of Times Sometimes, it’s necessary to limit the number of splits. The maxsplit parameter allows you to specify the maximum number of splits to be performed. text = "one#two#three#four" result = text.split('#', 2) print(result) Output: ['one', 'two', 'three#four'] In this example, the string was split into two parts, and the remaining portion after the second separator, 'three#four', was kept in the last list element. These examples demonstrate how flexible and useful the split() method can be in Python. Depending on your tasks, you can adapt its use to handle more complex string processing scenarios. Using the maxsplit Parameter The maxsplit parameter provides the ability to limit the number of splits a string will undergo. This can be useful when you only need a certain number of elements and do not require the entire string to be split. Let's take a closer look at how to use this parameter in practice. Limiting the Number of Splits Imagine you have a string containing a full file path, and you only need to extract the drive and the folder: path = "C:/Users/John/Documents/report.txt" parts = path.split('/', 2) print(parts) Output: ['C:', 'Users', 'John/Documents/report.txt'] Using maxsplit for Log File Processing Consider a string representing a log entry, where each part of the entry is separated by spaces. You are only interested in the first two fields—date and time. log_entry = "2024-10-23 11:15:32 User login successful" date_time = log_entry.split(' ', 2) print(date_time[:2]) Output: ['2024-10-23', '11:15:32'] In this case, we split the string twice and extract only the date and time, ignoring the rest of the entry. Application to CSV Data Sometimes, data may contain delimiter characters that you want to ignore after a certain point. csv_data = "Name,Email,Phone,Address" columns = csv_data.split(',', 2) print(columns) Output: ['Name', 'Email', 'Phone,Address'] Here, we limit the number of splits to keep the fields 'Phone' and 'Address' combined. The maxsplit parameter adds flexibility and control to the split() method, making it ideal for more complex data processing scenarios. Working with Delimiters Let’s examine how the split() method handles delimiters, including its default behavior and how to work with consecutive and multiple delimiters. Splitting by Default When no explicit delimiter is provided, the split() method splits the string by whitespace characters (spaces, tabs, and newlines). Additionally, consecutive spaces will be interpreted as a single delimiter, which is particularly useful when working with texts that may contain varying numbers of spaces between words. text = "Python is a versatile language" words = text.split() print(words) Output: ['Python', 'is', 'a', 'versatile', 'language'] Using a Single Delimiter Character If the string contains a specific delimiter, such as a comma or a colon, you can explicitly specify it as the sep argument. data = "red,green,blue,yellow" colors = data.split(',') print(colors) Output: ['red', 'green', 'blue', 'yellow'] In this case, the method splits the string wherever a comma is encountered. Working with Consecutive and Multiple Delimiters It’s important to note that when using a single delimiter character, split() does not treat consecutive delimiters as one. Each occurrence of the delimiter results in a new element in the resulting list, even if the element is empty. data = "one,,two,,,three" items = data.split(',') print(items) Output: ['one', '', 'two', '', '', 'three'] Splitting a String by Multiple Characters There are cases where you need to split a string using multiple delimiters or complex splitting rules. In such cases, it is recommended to use the re module and the re.split() function, which supports regular expressions. import re beverage_data = "coffee;tea juice|soda" beverages = re.split(r'[;|\s]', beverage_data) print(beverages) Output: ['coffee', 'tea', 'juice', 'soda'] In this example, a regular expression is used to split the string by several types of delimiters. Tips for Using the split() Method The split() method is a powerful and flexible tool for working with textual data in Python. To fully leverage its capabilities and avoid common pitfalls, here are some useful recommendations: Consider the Type of Delimiters When choosing a delimiter, make sure it matches the nature of the data. For instance, if the data contains multiple spaces, it might be more appropriate to use split() without explicitly specifying delimiters to avoid empty strings in the list. Use maxsplit for Optimization If you know that you only need a certain number of elements after splitting, use the maxsplit parameter to improve performance. This will also help avoid unexpected results when splitting long strings. Use Regular Expressions for Complex Cases The split() method with regular expressions enables solving more complex splitting tasks, such as when data contains multiple types of delimiters. Including the re library for this purpose significantly expands the method’s capabilities. Handle Empty Values When splitting a string with potentially missing values (e.g., when there are consecutive delimiters), make sure your code correctly handles empty strings or None. data = "value1,,value3" result = [item for item in data.split(',') if item] Validate Input Data Always consider potential errors, such as incorrect delimiters or unexpected data formats. Adding checks for values before calling split() can prevent many issues related to incorrect string splitting. Suitability for Use Remember that split() is unsuitable for processing more complex data structures, such as nested strings with quotes or data with escaped delimiters. In such cases, consider using specialized modules, such as csv for handling CSV formats. Following these tips, you can effectively use the split() method and solve textual data problems in Python. Understanding the subtleties of string splitting will help you avoid errors and make your code more reliable and understandable. Conclusion The split() method is an essential part of string handling in Python, providing developers with flexible and powerful tools for text splitting and data processing. In this article, we explored various aspects of using the split() method, including its syntax, working with parameters and delimiters, as well as practical examples and tips for its use. Check out our app platform to find Python applications, such as Celery, Django, FastAPI and Flask.
13 January 2025 · 8 min to read
Python

How to Convert a List to a Dictionary in Python

Python offers several fundamental data structures for storing data. Among the most popular are: List: Values with indices. Dictionary: Values with keys. Converting data from one type to another is essential to any dynamically typed programming language. Python, of course, is no exception. This guide will explain in detail what lists and dictionaries are and demonstrate various ways to convert one type to another. All examples in this article were executed using the Python interpreter version 3.10.12 on the Ubuntu 22.04 operating system, running on a Hostman cloud server. The list Type A list in Python is an ordered data structure of the "index-value" type. To create a list, use square brackets with values separated by commas: my_list = [False, True, 2, 'three', 4, 5] The list structure can be displayed in the console: print(my_list) The output will look like this: [False, True, 2, 'three', 4, 5] Accessing list values is done via indices: print(my_list[0]) # Output: False print(my_list[1]) # Output: True print(my_list[2]) # Output: 2 print(my_list[3]) # Output: three print(my_list[4]) # Output: 4 print(my_list[5]) # Output: 5 The dict Type A dictionary in Python is an unordered data structure of the "key-value" type. To create a dictionary, use curly braces with keys and values separated by colons and each pair separated by commas: my_dict = { 'James': '357 99 056 050', 'Natalie': '357 96 540 432', 'Kate': '357 96 830 726' } You can display the dictionary structure in the console as follows: print(my_dict) The output will look like this: {'James': '357 99 056 050', 'Natalie': '357 96 540 432', 'Kate': '357 96 830 726'} Accessing dictionary values is done via keys: print(my_dict['James']) # Output: 357 99 056 050 print(my_dict['Natalie']) # Output: 357 96 540 432 print(my_dict['Kate']) # Output: 357 96 830 726 Converting a List to a Dictionary You can convert a list to a dictionary in several ways: Use the dict.fromkeys() function, which creates a new dictionary with keys from the list. Use a dictionary comprehension with auxiliary functions and conditional operators. The latter option provides more flexibility for generating new dictionaries from existing lists. Creating Dictionary Keys from a List Using dict.fromkeys() The simplest way to create a dictionary from a list is to take the elements of a list instance and make them the keys of a dict instance. Optionally, you can add a default value for all keys in the new dictionary. This can be achieved using the standard dict.fromkeys() function. With this method, you can set a default value for all keys but not for individual keys. Here is an example of creating such a dictionary with keys from a list: objects = ['human', 'cat', 'alien', 'car'] # list of objects objects_states = dict.fromkeys(objects, 'angry') # create a dictionary with a default value for all keys objects_states_empty = dict.fromkeys(objects) # create a dictionary without specifying default values print(objects_states) # output the created dictionary with values print(objects_states_empty) # output the created dictionary without values Console output: {'human': 'angry', 'cat': 'angry', 'alien': 'angry', 'car': 'angry'} {'human': None, 'cat': None, 'alien': None, 'car': None} Creating a Dictionary from a List Using Dictionary Comprehension Another way to turn a list into dictionary keys is by using dictionary comprehension. This method is more flexible and allows for greater customization of the new dictionary. In its simplest form, the comprehension iterates over the list and copies all its elements as keys into a new dictionary, assigning them a specified default value. Here’s how to create a dictionary from a list using dictionary comprehension: objects = ['human', 'cat', 'alien', 'car'] objects_states = {obj: 'angry' for obj in objects} # dictionary comprehension with a string as the default value objects_states_empty = {obj: None for obj in objects} # dictionary comprehension with a default value of None print(objects_states) print(objects_states_empty) Console output: {'human': 'angry', 'cat': 'angry', 'alien': 'angry', 'car': 'angry'} {'human': None, 'cat': None, 'alien': None, 'car': None} In Python, the None object is a special value (null in most programming languages) that represents the absence of a value. The None object has a type of NoneType: print(type(None))  # Output: <class 'NoneType'> Creating a Dictionary from a List Using Dictionary Comprehension and the zip() Function A more advanced method is to use two lists to generate a dictionary: one for the keys and the other for their values. For this purpose, Python provides the zip() function, which allows iteration over multiple objects simultaneously. In simple loops, we can use this function like this: objects = ['human', 'cat', 'alien', 'car'] states = ['walking', 'purring', 'hiding', 'driving'] for obj, state in zip(objects, states): print(obj, state) The console output will be: human walking cat purring alien hiding car driving Thanks to this function, dictionary comprehension can simultaneously use elements from one list as keys and elements from another as values. In this case, the syntax for dictionary comprehension is not much different from a simple iteration: objects = ['human', 'cat', 'alien', 'car'] # list of future dictionary keys states = ['walking', 'purring', 'hiding', 'driving'] # list of future dictionary values objects_states = {obj: state for obj, state in zip(objects, states)} # dictionary comprehension iterating over both lists print(objects_states) Console output: {'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'} A natural question arises: what happens if one of the lists is shorter than the other? objects = ['human', 'cat', 'alien', 'car'] states = ['walking', 'purring'] objects_states = {obj: state for obj, state in zip(objects, states)} print(objects_states) The output will be: {'human': 'walking', 'cat': 'purring'} Thus, iteration in the dictionary comprehension stops at the shortest list. The code above can be written in a very compact form using the dict() constructor: objects = ['human', 'cat', 'alien', 'car'] states = ['walking', 'purring', 'hiding', 'driving'] objects_states = dict(zip(objects, states)) # create a dictionary from two lists without a for loop print(objects_states) The console output will be the same as in the previous examples: {'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'} Creating a Dictionary with zip() and Conditional Logic In real-world applications, logic is often more complex than the simple examples shown earlier. Sometimes, you need to convert lists into dictionaries while applying specific conditions. For instance, some elements might need modification before inclusion in the dictionary or might not be included at all. This can be achieved using conditions in dictionary comprehensions. For example, we can exclude specific elements from the resulting dictionary: objects = ['human', 'cat', 'alien', 'car'] states = ['walking', 'purring', 'hiding', 'driving'] objects_states = {obj: state for obj, state in zip(objects, states) if obj != 'alien'} # Protect Earth from unknown extraterrestrial influence print(objects_states) Console output: {'human': 'walking', 'cat': 'purring', 'car': 'driving'} We can refine the selection criteria further by introducing multiple conditions: objects = ['human', 'cat', 'alien', 'car'] states = ['walking', 'purring', 'hiding', 'driving'] objects_states = {obj: state for obj, state in zip(objects, states) if obj != 'alien' if obj != 'cat'} # Exclude the alien and the cat—who might be a disguised visitor from another galaxy print(objects_states) Console output: {'human': 'walking', 'car': 'driving'} When using multiple if statements in a dictionary comprehension, they behave as if connected by a logical and operator. You can make dictionary generation even more flexible by combining if and else operators: objects = ['human', 'cat', 'alien', 'car'] states = ['walking', 'purring', 'hiding', 'driving'] # In this example, all string elements in the first list are longer than those in the second list, except for 'cat' objects_states = { obj: ('[SUSPICIOUS]' if len(obj) < len(state) else 'calmly ' + state) for obj, state in zip(objects, states) } # Mark the suspicious 'cat' appropriately and slightly modify other values print(objects_states) Console output: {'human': 'calmly walking', 'cat': '[SUSPICIOUS]', 'alien': 'calmly hiding', 'car': 'calmly driving'} Creating a Complex Dictionary from a Single List In the earlier examples, we created dictionaries from two separate lists. But what if the keys and values needed for the new dictionary are contained within a single list? In such cases, the logic of the dictionary comprehension needs to be adjusted: objects_and_states = [ 'human', 'walking', 'cat', 'purring', 'alien', 'hiding', 'car', 'driving' ] # Keys and values are stored sequentially in one list objects_states = { objects_and_states[i]: objects_and_states[i + 1] for i in range(0, len(objects_and_states), 2) } # The `range` function specifies the start, end, and step for iteration: range(START, STOP, STEP) print(objects_states) Console output: {'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'} Sometimes, a list might contain nested dictionaries as elements. The values of these nested dictionaries can also be used to create a new dictionary. Here’s how the logic changes in such cases: objects = [ {'name': 'human', 'state': 'walking', 'location': 'street'}, {'name': 'cat', 'state': 'purring', 'location': 'windowsill'}, {'name': 'alien', 'state': 'hiding', 'location': 'spaceship'}, {'name': 'car', 'state': 'driving', 'location': 'highway'} ] objects_states = { obj['name']: obj['state'] for obj in objects } # Extract 'name' as key and 'state' as value print(objects_states) Console output: {'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'} This approach enables handling more complex data structures, such as lists of dictionaries, by targeting specific key-value pairs from each nested dictionary. Converting a Dictionary to a List Converting a dictionary into a list in Python is a straightforward task, often better described as extracting data. From a single dictionary, you can derive several types of lists: A list of keys A list of values A list of key-value pairs Here’s how it can be done: objects_states = { 'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving' } # Convert dictionary components to lists using the `list()` function objects_keys = list(objects_states.keys()) # List of keys objects_values = list(objects_states.values()) # List of values objects_items = list(objects_states.items()) # List of key-value pairs print(objects_keys) print(objects_values) print(objects_items) Console output: ['human', 'cat', 'alien', 'car'] ['walking', 'purring', 'hiding', 'driving'] [('human', 'walking'), ('cat', 'purring'), ('alien', 'hiding'), ('car', 'driving')] Conclusion Lists and dictionaries are fundamental data structures in Python, each offering distinct ways of storing and accessing data. Dictionaries are more informative than lists, storing data as key-value pairs, whereas lists store values that are accessed by index. Converting a dictionary into a list is straightforward, requiring no additional data since you’re simply extracting keys, values, or their pairs. Converting a list into a dictionary, on the other hand, requires additional data or rules to map the list elements to dictionary keys and values. There are a few methods to convert a List to Dictionary Tool Key Values Syntax dict.fromkeys() Common new_dict = dict.fromkeys(old_list) Dictionary Comprehension Common new_dict = {new_key: 'any value' for new_key in old_list} Dict Comp + zip() Unique new_dict = {new_key: old_val for new_key, old_val in zip(list1, list2)} Dict Comp + zip() + if Unique new_dict = {new_key: old_val for new_key, old_val in zip(list1, list2) if ...} Dict Comp + zip() + if-else Unique new_dict = {new_key: (... if ... else ...) for new_key, old_val in zip(list1, list2)} Complex lists may require more intricate dictionary comprehension syntax. Techniques shown in this guide, such as using zip() and range() for iterations, help handle such cases. Converting a dictionary to a list is also possible in several ways, but it is much simpler. Tool Extracts Syntax list.keys() Keys list(old_dict.keys()) list.values() Values list(old_dict.values()) list.items() Key-Value Pairs list(old_dict.items()) Python offers flexible and efficient ways to convert structured data types between lists and dictionaries, enabling powerful manipulation and access.
13 January 2025 · 11 min to read
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

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