How to Create an Array in Python

How to Create an Array in Python
Hostman Team
Technical writer
Python
23.11.2023
Reading time: 7 min

There are no classic arrays in Python by default: their functions are performed by lists. However, if necessary, the array creation function can be called. Therefore, to say that there are no arrays in Python is not entirely correct; they are still there, but you need to import a specific function to use them

Lists and arrays

The main difference between the two is that lists can store heterogeneous data, while arrays can only store data of the same type. For example, only strings or only numbers, and integers and floating-point numbers would be stored separately. 

So, this list in Python:

list = ['element1', 'element2', 'element3']

simultaneously performs the functions of an array. As you can see, the list elements are located inside square brackets and separated by commas. 

Here we took strings as an example. Let's look at another example:

>>> different = ['55', 'string', '32.5', ['list_in_list', '55', 'string', '32.5']]
>>> print(different)

['55', 'string', '32.5', ['list_in_list', '55', 'string', '32.5']]

This is also a list with array functions since all the elements here are formatted as strings. Now let's write the following:

>>> different2 = [55, 'string', 32.5, ['list_in_list', '55', 'string', '32*8']]
>>> print(different2)

[55, 'string', 32.5, ['list_in_list', '55', 'string', '32*8']]

Such a list is no longer a classic array since it combines heterogeneous elements: an integer, a string, a floating point number, and a list. So it turns out that lists include array functions, but their own functions are wider.

This is where the logical question arises: Why call a separate module to create arrays when you can use lists that include both functions? There is only one, but a good reason for this: called arrays are more compact and consume less memory. It is useful when working with resource-intensive applications and performing low-level operations.

Working with arrays

Further, we will not consider the classic lists but focus on working with called arrays. To import them, we should use the array module. Important note: The array function only allows you to create arrays from integer and floating-point values. Unicode characters are also supported for the time being, but starting with version 4.0, Python will no longer support Unicode. 

So, let's focus on int and float values.

Import array module 

So, the array function makes arrays available in a Python program. While it can be called using different methods, this one seems the most convenient, as it minimizes the number of subsequent errors:

from array import *

Of course, this command, like other general instructions, must be indicated in the "header" of the code, that is, at the very top.

Creating an array

To create an array, use the following pattern:

array_name = array(typecode,[ ])

Let's look at each element of the array in more detail:

  • array_name is the name (you can set any name that adheres to the rules for creating variables in Python);

  • array is the actual function;

  • typecode is the type of stored data (usually i for integer values, d for floating-point numbers);

  • inside the [ ] brackets you should list the array elements, separated by commas.

Now let's try to create a simple array:

>>> from array import *
>>> integers = array('i',[1,2,3,4,5])
>>> print(integers)

array('i', [1, 2, 3, 4, 5])

Okay, it works. Let's create an array with floating point numbers:

>>> from array import *
>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0])

But what happens if we replace the integer with a floating point number in the first example?

>>> integers = array('i',[1,2,3,4,5.2])

Traceback (most recent call last):
 File "<pyshell#26>", line 1, in <module>
   integers = array('i',[1,2,3,4,5.2])
TypeError: integer argument expected, got float

As expected, we receive an error; the interpreter expects an integer argument. 

Let’s use a different typecode:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4])
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0])

Here, we presented the last number as an integer, but no error occurred: the interpreter managed to convert it to the desired form in the output.

Array operations

You can perform various operations on arrays, just like on lists.

  • The len() function allows you to count the number of elements:

>>> integers = array('i',[1,2,3,4,5])
>>> print(len(integers))

5
  • You can also index the elements and display the ones you need (for this, use the print(array[number]) construct):

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> print(floats[0])

3.5

>>> print(floats[4])

4.0

>>> print(floats[1])

7.2

Note that numbering in Python always starts at zero, so to call the first element, we type print(floats[0]). Accordingly, the fifth element is number 4. And what happens if you try to call an element outside the array?

>>> print(floats[5])

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print(floats[5])
IndexError: array index out of range

The interpreter gives an error message informing us that the index is out of range. 

Sometimes, negative indexing may be required. In this case, the countdown starts from the last element, which gets index -1:

>>> print(floats[-1])

4.0

>>> print(floats[-2])

9.5

>>> print(floats[-5])

3.5

Module 5 works correctly with negative indexing since the numbering does not start from zero.

  • Loop operations are also available. This is how a sequence of elements is displayed using a for loop:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> for d in floats:
print(d)

3.5
7.2
5.3
9.5
4.0
  • Unlike strings, you can change arrays and lists in Python, so the following operations are also allowed:

>>> floats[1] = 8.2
>>> print(floats)

array('d', [3.5, 8.2, 5.3, 9.5, 4.0])

The value of the second element was 7.2, but we assigned a new one - 8.2.

  • If the values of the elements change, can we add a new element? To do this, use the append() method.

>>> integers = array('i',[1,2,3,4,5])
>>> integers.append(6)
>>> print(integers)

array('i', [1, 2, 3, 4, 5, 6])

The main thing is that the added element should be of the same data type as those already in the array, otherwise, the interpreter will give an error:

>>> integers.append(7.0)

Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
    integers.append(7.0)
TypeError: integer argument expected, got float
 

The error type indicates we entered a floating point number instead of the expected integer value. It is possible to convert the entered integer to a floating point number but it is not entirely correct to do so:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> floats.append(8)
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0, 8.0])
  • The extend() method will help you add multiple elements to an array. Enter this in the interpreter:

>>> floats.extend([4.5,5.7,6.9])
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])
  • And what if we need to insert a new element at some specific position? This is what the insert() method is for, and here's how to use it (we use the same modified array with floats from the example above):

>>> floats.insert(1,2.3)
>>> print(floats)

array('d', [3.5, 2.3, 7.2, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])

We inserted the number 2.3 in the second position (remember the numbering starts from zero, so the second position will be number 1).

  • Since you can add and insert elements, there must be a method for removing them. It's called remove():

>>> floats.remove(7.2)
>>> print(floats)

array('d', [3.5, 2.3, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])

And here's what happens if there are several elements in the array with the same value:

>>> integers = array('i',[11,12,13,14,15,11,11])
>>> integers.remove(11)
>>> print(integers)

array('i', [12, 13, 14, 15, 11, 11])
 

Only the first value, 11, was removed, while the rest remained in the array. To remove an element at a specific position, use the pop() method:

>>> integers = array('i',[11,12,13,14,15,11,11])
>>> integers.pop(5)

11

>>> print(integers)

array('i', [11, 12, 13, 14, 15, 11])

We have successfully removed the number 11 in the sixth position from the array.

Conclusion

Today, we learned about arrays in Python: how to create them and perform various operations. We also learned the advantages of called arrays over standard lists, which often perform the functions of both of these structures in Python.

If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.

Python
23.11.2023
Reading time: 7 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