How to Install Python on Windows 10

How to Install Python on Windows 10
Hostman Team
Technical writer
Python Windows
18.10.2024
Reading time: 5 min

Python is a high-level programming language used by millions of programmers and developers. It is intuitive, offers many useful tools and libraries, and is essential for working with and analyzing large datasets. However, Python is not pre-installed on Windows operating systems. This guide will walk you through installing Python on Windows 10.

Which Version to Choose

There are two main versions of Python: Python 2 and Python 3, and they are patible.

  • Python 3 was released in 2008 to address issues found in Python 2. It offers more straightforward, intuitive syntax, a wide range of useful libraries (especially for data analysis), and a large community supports it.

  • Python 2 is no longer supported, unlike Python 3. Therefore, for new projects, you only need Python 3. However, if you need to work on projects written in Python 2, you might still need this version, so we will also explain how to install it.

How to Install Python 2

To install Python 2 on Windows 10:

  1. Open your browser and go to the official website python.org.

  2. Go to the Downloads section.

  3. In the Downloads section, find the section for specific releases and locate the version you need.

Image3

  1. The last Python 2 release is 2.7.18. Click on Download and check the related files.

  2. For your operating system, download the 64-bit installer (it is the last file in the list).

Image6

  1. Once the file is downloaded, open it.

  2. Before starting the installation, the installer will allow you to choose the installation path and additional tools. Select the necessary options and start the installation.

How to Install Python 3 on Windows

There are several ways to install Python, each with its own features, advantages, and disadvantages:

  • Full Installation: Installs all components of Python, which is ideal for most projects.

  • Microsoft Store Installation: Suitable for development environments and running scripts.

  • NuGet Package Installation: Python comes as a ZIP file with the .nupkg extension, designed for continuous integration systems. It does not include the user interface. Ideal for building packages and running scripts.

  • Embeddable Package: Installs a minimal version of Python, often used as part of a larger application or project.

Full Installation Using the Official Installer

The steps for installing Python 3 from the official website are similar to those for Python 2. Here’s how to install Python 3 on Windows 10:

  1. Open your browser and go to python.org.

  2. Go to the Downloads section.

  3. Click on Download Python x.x.x (the latest version).

Image5

  1. Once you click it, the installer will start downloading.

  2. After downloading, open the installer.

  3. If Python 3 is already installed, the installer will offer to update it to the version you just downloaded. If Python is not installed, it will offer a fresh installation. Make sure to check the following options:

    • Installing for all users.

    • Add Python to PATH (this allows you to use Python from the command line).

  4. There are two installation options:

    • Install now:
      • Administrator rights are not required.

      • Python will be installed in your user directory.

      • Standard libraries, test suites, a launcher, and pip will be installed.

    • Customize Installation:
      • May require administrator rights.

      • Python will be installed in the Program Files directory.

      • Additional features can be installed.

      • The Python standard library can be precompiled into bytecode.

  1. Choose the option that suits you and start the installation. After it finishes, disable the MAX_PATH length limitation to avoid errors related to file path length.

To check if the installation was successful, run the command python --version in the command line. If everything went well, you should see an output like this:

Python 3.10.8

Python is now installed and ready to use.

Installing Python via Microsoft Store

To install Python from the Microsoft Store:

  1. Open the Microsoft Store application.

  2. In the search bar, type Python 3.x, specifying the version you want (e.g., "Python 3.10").

  3. Click Get.

  4. The download and installation will begin automatically.

Installing Python Using NuGet

To install Python on Windows via NuGet:

  1. Go to the official website and navigate to the Downloads section. Select the recommended version and download it.

  2. After opening the downloaded file, installation will take just a few seconds.

  3. To install Python, open Windows PowerShell and run the following commands:

For the 64-bit version:

nuget.exe install python -ExcludeVersion -OutputDirectory

For the 32-bit version:

nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory

Embeddable Package

The embeddable package provides a minimal Python environment. It is distributed as a ZIP file and is intended to integrate Python into larger applications. The embeddable package is not designed for direct user access.

You will have a fully isolated Python environment when extracted from the archive. It will be isolated from the user’s operating system, including environment variables (like PATH), the system registry, and any installed packages. The standard Python library is included in the embeddable package as compiled and optimized files. However, this version does not include a package manager (pip) or documentation.

You can download the embeddable package from the python.org website:

  1. Go to the Downloads section.

  2. Clicking on Download will download the regular version, so click the hyperlink for Python for Windows instead.

Image4

  1. Click Latest Python 3 Release - Python x.x.x.

Image1

  1. Scroll down to the Files section and choose one of the embeddable versions (for 64-bit or 32-bit systems).

Image2

Conclusion

This guide has covered various methods for installing Python on Windows 10. For more useful Python resources, you can explore our tutorials. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.

Python Windows
18.10.2024
Reading time: 5 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