{"id":134554,"date":"2023-09-01T08:13:33","date_gmt":"2023-09-01T08:13:33","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=1651200"},"modified":"2023-09-01T08:13:33","modified_gmt":"2023-09-01T08:13:33","slug":"python-create-dictionary-the-ultimate-guide","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/09\/01\/python-create-dictionary-the-ultimate-guide\/","title":{"rendered":"Python Create Dictionary \u2013 The Ultimate Guide"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1651200&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;4&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;4\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;Python Create Dictionary - The Ultimate Guide&quot;,&quot;width&quot;:&quot;113.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 113.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 4\/5 &#8211; (1 vote) <\/div>\n<\/p><\/div>\n<h2 class=\"wp-block-heading\">Introduction to Python Dictionaries<\/h2>\n<p>A <a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\">Python dictionary<\/a> is a built-in data structure that allows you to store data in the form of key-value pairs. It offers an efficient way to organize and access your data.<\/p>\n<p class=\"has-global-color-8-background-color has-background\">In Python, creating a dictionary is easy. You can use the <code><a href=\"https:\/\/blog.finxter.com\/python-dict\/\">dict()<\/a><\/code> function or simply use curly braces <code>{}<\/code> to define an empty dictionary. <\/p>\n<p>For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_dictionary = {}<\/pre>\n<p>This will create an empty dictionary called <code>my_dictionary<\/code>. To add data to the dictionary, you can use the following syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_dictionary = { \"key1\": \"value1\", \"key2\": \"value2\"\n}\n<\/pre>\n<p>In this case, <code>\"key1\"<\/code> and <code>\"key2\"<\/code> are the keys, while <code>\"value1\"<\/code> and <code>\"value2\"<\/code> are the corresponding values. Remember that the keys must be unique, as duplicate keys are not allowed in <a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\">Python dictionaries<\/a>.<\/p>\n<p>One of the reasons why dictionaries are important in programming projects is their efficient access and manipulation of data. When you need to retrieve a value, simply provide the corresponding key:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">value = my_dictionary[\"key1\"]\n<\/pre>\n<p>This will return the value associated with <code>\"key1\"<\/code>, in this case, <code>\"value1\"<\/code>. If the key does not exist in the dictionary, Python will raise a <code>KeyError<\/code>.<\/p>\n<p>Dictionaries also support various methods for managing the data, such as updating the values, deleting keys, or iterating through the key-value pairs. <\/p>\n<h2 class=\"wp-block-heading\">Basic Dictionary Creation<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" fetchpriority=\"high\" width=\"1024\" height=\"686\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-1-1024x686.png\" alt=\"\" class=\"wp-image-1651209\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-1-1024x686.png 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-1-300x201.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-1-768x514.png 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-1.png 1047w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<p>In this section, we will discuss the basic methods of creating dictionaries.<\/p>\n<p>To create an empty dictionary, you can use a pair of curly braces, <code>{}<\/code>. This will initialize an empty dictionary with no elements. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">empty_dict = {}\n<\/pre>\n<p>Another method to create an empty dictionary is using the <code>dict()<\/code> function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">another_empty_dict = dict()\n<\/pre>\n<p>Once you have an empty dictionary, you can start populating it with key-value pairs. To add elements to your dictionary, use the assignment operator <code>=<\/code> and square brackets <code>[]<\/code> around the key:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Creating an empty dictionary\nmy_dict = {} # Adding a key-value pair for \"apple\" and \"fruit\"\nmy_dict[\"apple\"] = \"fruit\" <\/pre>\n<p>Alternatively, you can define key-value pairs directly in the dictionary using the curly braces <code>{}<\/code> method. In this case, each key is separated from its corresponding value by a colon <code>:<\/code>, and the key-value pairs are separated by commas <code>,<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fruits_dict = { \"apple\": \"fruit\", \"banana\": \"fruit\", \"carrot\": \"vegetable\",\n}\n<\/pre>\n<p>The <code>dict()<\/code> function can also be used to create a dictionary by passing a <a href=\"https:\/\/blog.finxter.com\/how-to-access-elements-from-a-list-of-tuples\/\">list of tuples<\/a>, where each tuple is a key-value pair:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fruits_list = [(\"apple\", \"fruit\"), (\"banana\", \"fruit\"), (\"carrot\", \"vegetable\")]\nfruits_dict = dict(fruits_list)\n<\/pre>\n<\/p>\n<h2 class=\"wp-block-heading\">Creating Dictionaries from Lists and Arrays<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"686\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3768126-1024x686.jpeg\" alt=\"\" class=\"wp-image-1651210\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3768126-1024x686.jpeg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3768126-300x201.jpeg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3768126-768x515.jpeg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3768126.jpeg 1119w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Python Create Dict From List<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">To create a dictionary from a list, first make sure that the list contains mutable pairs of keys and values. One way to achieve this is by using the <code><a href=\"https:\/\/blog.finxter.com\/python-zip-get-elements-from-multiple-lists\/\">zip()<\/a><\/code> function. The <code>zip()<\/code> function allows you to combine two lists into a single list of pairs. <\/p>\n<p>For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\ncombined_list = zip(keys, values)\n<\/pre>\n<p>Next, use the <code>dict()<\/code> function to convert the combined list into a dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dictionary = dict(combined_list)\nprint(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3}\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Two Lists<\/h3>\n<p>To create a dictionary from two separate lists, you can utilize the <code>zip()<\/code> function along with a dictionary comprehension. This method allows you to easily iterate through the lists and create key-value pairs simultaneously:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\ndictionary = {key: value for key, value in zip(keys, values)}\nprint(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3}\n<\/pre>\n<p>The <a href=\"https:\/\/blog.finxter.com\/how-to-create-a-dictionary-from-two-lists\/\">How to Create a Dictionary from two Lists<\/a> post provides a detailed explanation of this process.<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From List Comprehension<\/h3>\n<p><a href=\"https:\/\/blog.finxter.com\/list-comprehension-in-python\/\">List comprehension<\/a> is a powerful feature in Python that allows you to create a new list by applying an expression to each element in an existing list or other iterable data types. You can also use list comprehension to create a dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\ndictionary = {keys[i]: values[i] for i in range(len(keys))}\nprint(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3}\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From List in One Line<\/h3>\n<p>To create a dictionary from a list in just one line of code, you can use the <code>zip()<\/code> function and the <code>dict()<\/code> function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\ndictionary = dict(zip(keys, values))\nprint(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3}\n<\/pre>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-create-dictionary-the-ultimate-guide\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTlEC5Jx72Uc%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p class=\"has-base-2-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-dictionary-comprehension\/\">Python Dictionary Comprehension: A Powerful One-Liner Tutorial<\/a><\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From a List of Tuples<\/h3>\n<p>If you have a list of tuples, where each tuple represents a key-value pair, you can create a dictionary using the <code>dict()<\/code> function directly:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">list_of_tuples = [('a', 1), ('b', 2), ('c', 3)]\ndictionary = dict(list_of_tuples)\nprint(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3}\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Array<\/h3>\n<p>To create a dictionary from an array or any sequence data type, first convert it into a list of tuples, where each tuple represents a key-value pair. Then, use the <code>dict()<\/code> function to create the dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np array = np.array([['a', 1], ['b', 2], ['c', 3]])\nlist_of_tuples = [tuple(row) for row in array]\ndictionary = dict(list_of_tuples)\nprint(dictionary) # Output: {'a': '1', 'b': '2', 'c': '3'}\n<\/pre>\n<p>Note that the values in this example are strings because the NumPy array stores them as a single data type. You can later convert these <a href=\"https:\/\/blog.finxter.com\/python-strings-made-easy\/\">strings<\/a> back to integers if needed.<\/p>\n<h2 class=\"wp-block-heading\">Creating Dictionaries from Strings and Enumerations<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1194036-1024x683.webp\" alt=\"\" class=\"wp-image-1651211\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1194036-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1194036-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1194036-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1194036.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Python Create Dict From String<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">To create a dictionary from a string, you can use a combination of string manipulation and <a href=\"https:\/\/blog.finxter.com\/python-dictionary-comprehension\/\">dictionary comprehension<\/a>. This method allows you to extract key-value pairs from the given string, and subsequently populate the dictionary. <\/p>\n<p>The following example demonstrates how to create a dictionary from a string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">input_string = \"name=John Doe, age=25, city=New York\"\nstring_list = input_string.split(\", \") dictionary = {item.split(\"=\")[0]: item.split(\"=\")[1] for item in string_list}\nprint(dictionary)\n<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{'name': 'John Doe', 'age': '25', 'city': 'New York'}\n<\/pre>\n<p>In this example, the input string is split into a list of smaller strings using <code>,<\/code> as the separator. Then, a dictionary comprehension is used to split each pair by the <code>=<\/code> sign, creating the key-value pairs.<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict from Enumerate<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">The <code><a href=\"https:\/\/blog.finxter.com\/python-enumerate\/\">enumerate()<\/a><\/code> function can also be used to create a dictionary. This function allows you to create key-value pairs, where the key is the index of a list item, and the value is the item itself. <\/p>\n<p>Here is an example of using <code>enumerate()<\/code> to create a dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">input_list = [\"apple\", \"banana\", \"orange\"]\ndictionary = {index: item for index, item in enumerate(input_list)}\nprint(dictionary)\n<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{0: 'apple', 1: 'banana', 2: 'orange'}\n<\/pre>\n<p>In this example, the <code>enumerate()<\/code> function is used in a dictionary comprehension to create key-value pairs with the index as the key and the list item as the value.<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From Enum<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">Python includes an <code>Enum<\/code> class, which can be used to create enumerations. Enumerations are a way to define named constants that have a specific set of values. To create a dictionary from an enumeration, you can loop through the enumeration and build key-value pairs. <\/p>\n<p>Here&#8217;s an example of creating a dictionary from an enumeration:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 dictionary = {color.name: color.value for color in Color}\nprint(dictionary)\n<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{'RED': 1, 'GREEN': 2, 'BLUE': 3}\n<\/pre>\n<p>In this example, an enumeration called <code>Color<\/code> is defined and then used in a dictionary comprehension to create key-value pairs with the color name as the key and the color value as the value.<\/p>\n<p>When working with dictionaries in Python, it&#8217;s essential to be aware of potential <code>KeyError<\/code> exceptions that can occur when trying to access an undefined key in a dictionary. This can be handled using the <code><a href=\"https:\/\/blog.finxter.com\/python-dict-get-method\/\">dict.get()<\/a><\/code> method, which returns a specified default value if the requested key is not found. <\/p>\n<p>Also, updating the dictionary&#8217;s key-value pairs is a simple process using the assignment operator, which allows you to either add a new entry to the dictionary or update the value for an existing key. <\/p>\n<h2 class=\"wp-block-heading\">Creating Dictionaries from Other Dictionaries<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"500\" height=\"750\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-6550124.webp\" alt=\"\" class=\"wp-image-1651212\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-6550124.webp 500w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-6550124-200x300.webp 200w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/figure>\n<\/div>\n<p>In this section, you&#8217;ll learn how to create new dictionaries from existing ones. We&#8217;ll cover how to create a single dictionary from another one, create one from two separate dictionaries, create one from multiple dictionaries, and finally, create one from a nested dictionary.<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From Another Dict<\/h3>\n<p>To create a new dictionary from an existing one, you can use a dictionary comprehension. The following code snippet creates a new dictionary with keys and values from the old one, in the same order.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">old_dict = {'a': 1, 'b': 2, 'c': 3}\nnew_dict = {k: v for k, v in old_dict.items()}\n<\/pre>\n<p>If you want to modify the keys or values in the new dictionary, simply apply the modifications within the comprehension:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">new_dict_modified = {k * 2: v for k, v in old_dict.items()}\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Two Dicts<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">Suppose you want to combine two dictionaries into one. You can do this using the <code><a href=\"https:\/\/blog.finxter.com\/python-dictionary-update-method\/\">update()<\/a><\/code> method or union operator <code>|<\/code>. The <code>update()<\/code> method can add or modify the keys from the second dictionary in the first one. <\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dict1 = {'a': 1, 'b': 2}\ndict2 = {'b': 3, 'c': 4}\ndict1.update(dict2)\n<\/pre>\n<p>If you&#8217;re using <a href=\"https:\/\/blog.finxter.com\/whats-new-in-python-3-9\/\">Python 3.9<\/a> or later, you can utilize the <a href=\"https:\/\/blog.finxter.com\/python-set-union\/\">union<\/a> operator <code>|<\/code> to combine two dictionaries:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">combined_dict = dict1 | dict2\n<\/pre>\n<p>Keep in mind that in case of overlapping keys, the values from the second dictionary will take precedence.<\/p>\n<h3 class=\"wp-block-heading\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4ab.png\" alt=\"\ud83d\udcab\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> Master Tip: Python Create Dict From Multiple Dicts<\/h3>\n<p>If you want to combine multiple dictionaries into one, you can use the <code>**<\/code> <a href=\"https:\/\/blog.finxter.com\/python-unpacking\/\">unpacking operator<\/a> in a new dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dict1 = {'a': 1, 'b': 2}\ndict2 = {'b': 3, 'c': 4}\ndict3 = {'d': 5} combined_dict = {**dict1, **dict2, **dict3}\n<\/pre>\n<p>The <code>combined_dict<\/code> will contain all the keys and values from <code>dict1<\/code>, <code>dict2<\/code>, and <code>dict3<\/code>. In case of overlapping keys, the values from later dictionaries will replace those from the earlier ones.<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From Nested Dict<\/h3>\n<p>When working with a <a href=\"https:\/\/blog.finxter.com\/python-get-values-from-a-nested-dictionary\/\">nested dictionary<\/a>, you might want to create a new dictionary from a sub-dictionary. To do this, use the key to access the nested dictionary, and then make a new dictionary from the sub-dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">nested_dict = {'a': {'x': 1, 'y': 2}, 'b': {'z': 3}}\nsub_dict = nested_dict['a']\nnew_dict = {k: v for k, v in sub_dict.items()}\n<\/pre>\n<p>In the code above, the <code>new_dict<\/code> will be created from the sub-dictionary with the key <code>'a'<\/code>.<\/p>\n<\/p>\n<h2 class=\"wp-block-heading\">Creating Dictionaries from Files and Data Formats<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1181772-1024x683.webp\" alt=\"\" class=\"wp-image-1651213\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1181772-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1181772-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1181772-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-1181772.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<p>In this section, we will explore ways to create Python dictionaries from various file formats and data structures. We will cover the following topics:<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From CSV<\/h3>\n<p>Creating a dictionary from a CSV file can be achieved using Python&#8217;s built-in <code>csv<\/code> module. First, open the CSV file with a <a href=\"https:\/\/blog.finxter.com\/python-one-line-with-statement\/\"><code>with<\/code> statement<\/a> and then use <code>csv.DictReader<\/code> to iterate over the rows, creating a dictionary object for each row:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import csv with open('input.csv', 'r') as csvfile: reader = csv.DictReader(csvfile) my_dict = {} for row in reader: key = row['key_column'] my_dict[key] = row\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Dataframe<\/h3>\n<p>When working with Pandas DataFrames, you can generate a dictionary from the underlying data using the <code><a href=\"https:\/\/blog.finxter.com\/pandas-dataframe-to_dict-method\/\">to_dict()<\/a><\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd df = pd.read_csv('input.csv') my_dict = df.set_index('key_column').to_dict('index')\n<\/pre>\n<p>This will create a dictionary where the DataFrame index is set as keys and the remaining data as values.<\/p>\n<h3 class=\"wp-block-heading\">Python Create Dict From Dataframe Columns<\/h3>\n<p>To create a dictionary from specific DataFrame columns, use the <code>zip<\/code> function and the <code>to_dict()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_dict = dict(zip(df['key_column'], df['value_column']))\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Excel<\/h3>\n<p>Openpyxl is a Python library that helps you work with Excel (<code>.xlsx<\/code>) files. Use it to read the file, iterate through the rows, and add the data to a dictionary:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import openpyxl workbook = openpyxl.load_workbook('input.xlsx')\nsheet = workbook.active my_dict = {}\nfor row in range(2, sheet.max_row + 1): key = sheet.cell(row=row, column=1).value value = sheet.cell(row=row, column=2).value my_dict[key] = value\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From YAML File<\/h3>\n<p>To create a dictionary from a YAML file, you can use the <code>PyYAML<\/code> library. Install it using <code><a href=\"https:\/\/blog.finxter.com\/fixed-modulenotfounderror-no-module-named-types-pyyaml\/\">pip install PyYAML<\/a><\/code>. Then read the YAML file and convert it into a dictionary object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import yaml with open('input.yaml', 'r') as yaml_file: my_dict = yaml.safe_load(yaml_file)\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Json File<\/h3>\n<p>To generate a dictionary from a JSON file, use Python&#8217;s built-in <code>json<\/code> module to read the file and decode the JSON data:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import json with open('input.json', 'r') as json_file: my_dict = json.load(json_file)\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Text File<\/h3>\n<p>To create a dictionary from a text file, you can read its contents and use some custom logic to parse the keys and values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">with open('input.txt', 'r') as text_file: lines = text_file.readlines() my_dict = {}\nfor line in lines: key, value = line.strip().split(':') my_dict[key] = value\n<\/pre>\n<p>Modify the parsing logic according to the format of your input text file. This will ensure you correctly store the data as keys and values in your dictionary.<\/p>\n<h2 class=\"wp-block-heading\">Advanced Dictionary Creation Methods<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-7092613-1024x683.webp\" alt=\"\" class=\"wp-image-1651214\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-7092613-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-7092613-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-7092613-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-7092613.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Python Create Dict From Variables<\/h3>\n<p>You can create a dictionary from variables using the <code>dict()<\/code> function. This helps when you have separate variables for keys and values. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">key1 = \"a\"\nvalue1 = 1\nkey2 = \"b\"\nvalue2 = 2 my_dict = dict([(key1, value1), (key2, value2)])\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Arguments<\/h3>\n<p>Another way to create dictionaries is by using the <code>**kwargs<\/code> feature in Python. This allows you to pass keyword arguments to a function and create a dictionary from them. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_dict(**kwargs): return kwargs my_dict = create_dict(a=1, b=2, c=3)\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Iterator<\/h3>\n<p>You can also create a dictionary by iterating over a list and using list comprehensions, along with the <code><a href=\"https:\/\/blog.finxter.com\/python-dict-get-method\/\">get()<\/a><\/code> method. This is useful if you need to count occurrences of certain elements:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_list = ['a', 'b', 'a', 'c', 'b']\nmy_dict = {} for item in my_list: my_dict[item] = my_dict.get(item, 0) + 1\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From User Input<\/h3>\n<p>To create a dictionary from user input, you can use a for loop. Prompt users to provide input and create the dictionary with the key-value pairs they provide:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_dict = {} for i in range(3): key = input(\"Enter key: \") value = input(\"Enter value: \") my_dict[key] = value\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict From Object<\/h3>\n<p>You can create a dictionary from an object&#8217;s attributes using the built-in <code>vars()<\/code> function. This is helpful when converting an object to a dictionary. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class MyObject: def __init__(self, a, b, c): self.a = a self.b = b self.c = c my_obj = MyObject(1, 2, 3)\nmy_dict = vars(my_obj)\n<\/pre>\n<h3 class=\"wp-block-heading\">Python Create Dict Zip<\/h3>\n<p>Lastly, you can create a dictionary using the <code>zip()<\/code> function and the <code>dict()<\/code> constructor. This is useful when you have two lists \u2014 one representing keys and the other representing values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">keys = ['a', 'b', 'c']\nvalues = [1, 2, 3] my_dict = dict(zip(keys, values))\n<\/pre>\n<\/p>\n<h2 class=\"wp-block-heading\">Frequently Asked Questions<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-8199166-1024x683.webp\" alt=\"\" class=\"wp-image-1651215\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-8199166-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-8199166-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-8199166-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-8199166.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">How do you create an empty dictionary in Python?<\/h3>\n<p>To create an empty dictionary in Python, you can use either a set of curly braces <code>{}<\/code> or the built-in <code>dict()<\/code> function. Here are examples of both methods:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">empty_dict1 = {}\nempty_dict2 = dict()\n<\/pre>\n<h3 class=\"wp-block-heading\">What are common ways to create a dictionary from two lists?<\/h3>\n<p>To create a dictionary from two lists, you can use the <code>zip<\/code> function in combination with the <code>dict()<\/code> constructor. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nmy_dict = dict(zip(keys, values))\n<\/pre>\n<p>In this example, <code>my_dict<\/code> will be <code>{'a': 1, 'b': 2, 'c': 3}<\/code>.<\/p>\n<h3 class=\"wp-block-heading\">What are the key dictionary methods in Python?<\/h3>\n<p>Some common dictionary methods in Python include:<\/p>\n<ul>\n<li><code>get(key, default)<\/code>: Returns the value associated with the key if it exists; otherwise, returns the default value.<\/li>\n<li><code>update(other)<\/code>: Merges the current dictionary with another dictionary or other key-value pairs.<\/li>\n<li><code>keys()<\/code>: Returns a view object displaying all the keys in the dictionary.<\/li>\n<li><code>values()<\/code>: Returns a view object displaying all the values in the dictionary.<\/li>\n<li><code>items()<\/code>: Returns a view object displaying all the key-value pairs in the dictionary.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">How do I create a dictionary if it does not exist?<\/h3>\n<p>You can use a conditional statement along with the <code>globals()<\/code> function to create a dictionary if it does not exist. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">if 'my_dict' not in globals(): my_dict = {'a': 1, 'b': 2, 'c': 3}\n<\/pre>\n<p>In this case, <code>my_dict<\/code> will only be created if it does not already exist in the global namespace.<\/p>\n<h3 class=\"wp-block-heading\">How can I loop through a dictionary in Python?<\/h3>\n<p>You can loop through a dictionary in Python using the <code><a href=\"https:\/\/blog.finxter.com\/python-dict-items-method\/\">items()<\/a><\/code> method, which returns key-value pairs. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(f'{key}: {value}')\n<\/pre>\n<p>This code will output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">a: 1\nb: 2\nc: 3\n<\/pre>\n<h3 class=\"wp-block-heading\">What is an example of a dictionary in Python?<\/h3>\n<p>A dictionary in Python is a collection of key-value pairs enclosed in curly braces. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_dict = { 'apple': 3, 'banana': 2, 'orange': 4\n}\n<\/pre>\n<p>In this example, the keys are fruit names, and the values are quantities.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"501\" height=\"750\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5530485.webp\" alt=\"\" class=\"wp-image-1651216\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5530485.webp 501w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5530485-200x300.webp 200w\" sizes=\"auto, (max-width: 501px) 100vw, 501px\" \/><\/figure>\n<\/div>\n<p class=\"has-base-2-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\">Python Dictionary \u2013 The Ultimate Guide<\/a><\/p>\n<h2 class=\"wp-block-heading\">Python One-Liners Book: Master the Single Line First!<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<\/div>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: <strong><em>concise statements of useful functionality packed into a single line of code. <\/em><\/strong>You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. <\/p>\n<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts <\/em><\/strong>and<strong><em> boost your coding and analytical skills<\/em><\/strong>. You&#8217;ll learn about advanced Python features such as <em><strong>list comprehension<\/strong><\/em>, <strong><em>slicing<\/em><\/strong>, <strong><em>lambda functions<\/em><\/strong>, <strong><em>regular expressions<\/em><\/strong>, <strong><em>map <\/em><\/strong>and <strong><em>reduce <\/em><\/strong>functions, and <strong><em>slice assignments<\/em><\/strong>. <\/p>\n<p>You&#8217;ll also learn how to:<\/p>\n<ul>\n<li>Leverage data structures to <strong>solve real-world problems<\/strong>, like using Boolean indexing to find cities with above-average pollution<\/li>\n<li>Use <strong>NumPy basics<\/strong> such as <em>array<\/em>, <em>shape<\/em>, <em>axis<\/em>, <em>type<\/em>, <em>broadcasting<\/em>, <em>advanced indexing<\/em>, <em>slicing<\/em>, <em>sorting<\/em>, <em>searching<\/em>, <em>aggregating<\/em>, and <em>statistics<\/em><\/li>\n<li>Calculate basic <strong>statistics <\/strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning<\/li>\n<li>Create more <strong>advanced regular expressions<\/strong> using <em>grouping <\/em>and <em>named groups<\/em>, <em>negative lookaheads<\/em>, <em>escaped characters<\/em>, <em>whitespaces, character sets<\/em> (and <em>negative characters sets<\/em>), and <em>greedy\/nongreedy operators<\/em><\/li>\n<li>Understand a wide range of <strong>computer science topics<\/strong>, including <em>anagrams<\/em>, <em>palindromes<\/em>, <em>supersets<\/em>, <em>permutations<\/em>, <em>factorials<\/em>, <em>prime numbers<\/em>, <em>Fibonacci <\/em>numbers, <em>obfuscation<\/em>, <em>searching<\/em>, and <em>algorithmic sorting<\/em><\/li>\n<\/ul>\n<p>By the end of the book, you&#8217;ll know how to <strong><em>write Python at its most refined<\/em><\/strong>, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners on Amazon!!<\/em><\/a><\/strong><\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/blog.finxter.com\/python-create-dictionary-the-ultimate-guide\/\">Python Create Dictionary &#8211; The Ultimate Guide<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/blog.finxter.com\">Be on the Right Side of Change<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>4\/5 &#8211; (1 vote) Introduction to Python Dictionaries A Python dictionary is a built-in data structure that allows you to store data in the form of key-value pairs. It offers an efficient way to organize and access your data. In Python, creating a dictionary is easy. You can use the dict() function or simply use [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-134554","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134554","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=134554"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134554\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=134554"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=134554"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=134554"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}