{"id":114797,"date":"2020-06-29T08:20:22","date_gmt":"2020-06-29T08:20:22","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10194"},"modified":"2020-06-29T08:20:22","modified_gmt":"2020-06-29T08:20:22","slug":"dict-to-list-how-to-convert-a-dictionary-to-a-list-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/29\/dict-to-list-how-to-convert-a-dictionary-to-a-list-in-python\/","title":{"rendered":"Dict to List \u2014 How to Convert a Dictionary to a List in Python"},"content":{"rendered":"<p class=\"has-black-color has-luminous-vivid-amber-background-color has-text-color has-background\"><strong>Summary<\/strong>: To convert a dictionary to a list of tuples, use the <code>dict.items()<\/code> method to obtain an iterable of <code>(key, value)<\/code> pairs and convert it to a list using the <code>list(...)<\/code> constructor: <code>list(dict.items())<\/code>. To modify each key value pair before storing it in the list, you can use the list comprehension statement <code>[(k', v') for k, v in dict.items()]<\/code> replacing <code>k'<\/code> and <code>v'<\/code> with your specific modifications.<\/p>\n<p>In my code projects, I often find that choosing the right data structure is an important prerequisite to writing clean and effective code. In this article, you&#8217;ll learn the most Pythonic way to <em>convert a <a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" title=\"Python Dictionary \u2013 The Ultimate Guide\" target=\"_blank\" rel=\"noreferrer noopener\">dictionary <\/a>to a <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" title=\"The Ultimate Guide to Python Lists\" target=\"_blank\" rel=\"noreferrer noopener\">list<\/a><\/em>.<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Dict to List \u2014 How to Convert a Dictionary to a List in Python\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/LD5vqxyIpMM?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><strong>Problem<\/strong>: Given a dictionary of <code>key:value<\/code> pairs. Convert it to a list of <code>(key, value)<\/code> tuples.<\/p>\n<p><strong>Example<\/strong>: Given the following 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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47}<\/pre>\n<p>You want to convert it to a list of <code>(key, value)<\/code> tuples:<\/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=\"\">[('Alice', 19), ('Bob', 23), ('Carl', 47)]<\/pre>\n<p>You can get a quick overview of the methods examined in this article next:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/63517365f5\" width=\"100%\" height=\"600\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Change the data structure of the dictionary elements. Does it still work?<\/em><\/p>\n<p>Let&#8217;s dive into the methods!<\/p>\n<h2>Method 1: List of Tuples with dict.items() + list()<\/h2>\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/dict_to_lists-1024x576.jpg\" alt=\"dict to list python\" class=\"wp-image-10211\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/dict_to_lists-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/dict_to_lists-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/dict_to_lists-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p>The first approach uses the dictionary method <code>dict.items()<\/code> to retrieve an iterable of <code>(key, value)<\/code> tuples. The only thing left is to convert it to a list using the built-in <code>list()<\/code> constructor.<\/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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 1\nt = list(d.items())\nprint(t)\n# [('Alice', 19), ('Bob', 23), ('Carl', 47)]<\/pre>\n<p>The variable <code>t<\/code> now holds a list of <code>(key, value)<\/code> tuples. Note that in many cases, it&#8217;s not necessary to actually convert it to a list, and, thus, instantiate the data structure in memory. For example, if you want to loop over all <code>(key, value)<\/code> pairs in the dictionary, you can do so without conversion:<\/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=\"\">for k,v in d.items(): s = str(k) + '->' + str(v) print(s) '''\nAlice->19\nBob->23\nCarl->47 '''<\/pre>\n<p>Using the <code>items()<\/code> method on the dictionary object is the most Pythonic way if everything you want is to retrieve a list of <code>(key, value)<\/code> pairs. However, what if you want to get a list of keys&#8212;ignoring the values for now?<\/p>\n<h2>Method 2: List of Keys with dict.key()<\/h2>\n<p>To get a list of key values, use the <code>dict.keys()<\/code> method and pass the resulting iterable into a <code>list()<\/code> constructor.<\/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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 2\nt = list(d.keys())\nprint(t)\n# ['Alice', 'Bob', 'Carl']<\/pre>\n<p>Similarly, you may want to get a list of values.<\/p>\n<h2>Method 3: List of Values with dict.values()<\/h2>\n<p>To get a list of key values, use the <code>dict.values()<\/code> method and pass the resulting iterable into a <code>list()<\/code> constructor.<\/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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 3\nt = list(d.values())\nprint(t)\n# [19, 23, 47]<\/pre>\n<p>But what if you want to modify each <code>(key, value)<\/code> tuple? Let&#8217;s study some alternatives.<\/p>\n<h2>Method 4: List Comprehension with dict.items()<\/h2>\n<p><a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">List comprehension<\/a> is a compact way of creating lists. The simple formula is <code>[expression + context]<\/code>.<\/p>\n<ul>\n<li><strong>Expression: <\/strong>What to do with each list element?<\/li>\n<li><strong>Context:<\/strong> What elements to select? The context consists of an arbitrary number of <code>for<\/code> and <code>if<\/code> statements.<\/li>\n<\/ul>\n<p>You can use list comprehension to modify each <code>(key, value)<\/code> pair from the original dictionary before you store the result in the new list.<\/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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 4\nt = [(k[:3], v-1) for k, v in d.items()]\nprint(t)\n# [('Ali', 18), ('Bob', 22), ('Car', 46)]<\/pre>\n<p>You transform each key to a string with three characters using <a href=\"https:\/\/blog.finxter.com\/introduction-to-slicing-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Introduction to Slicing in Python\">slicing <\/a>and reduce each value by one.<\/p>\n<h2>Method 5: zip() with dict.keys() and dict.values()<\/h2>\n<p>Just for comprehensibility, you could (theoretically) use the <a href=\"https:\/\/blog.finxter.com\/zip-unzip-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Zip &amp; Unzip: How Does It Work in Python?\"><code>zip()<\/code> function <\/a>to create a <a href=\"https:\/\/blog.finxter.com\/how-to-merge-lists-into-a-list-of-tuples\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Merge Lists into a List of Tuples? [6 Pythonic Ways]\">list of tuples<\/a>:<\/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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 5\nt = list(zip(d.keys(), d.values()))\nprint(t)\n# [('Alice', 19), ('Bob', 23), ('Carl', 47)]\n<\/pre>\n<p>However, there&#8217;s no benefit compared to just using the <code>dict.items()<\/code> method. However, I wanted to show you this because the <code><a href=\"https:\/\/blog.finxter.com\/python-ziiiiiiip-a-helpful-guide\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Ziiiiiiip! [A helpful guide]\">zip()<\/a><\/code> function is frequently used in Python and it&#8217;s important for you to understand it. <\/p>\n<h2>Method 6: Basic Loop<\/h2>\n<p>The last method uses a basic for <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Loops\">loop<\/a>&#8212;not the worst way of doing it! Sure, a Python pro would use the most Pythonic ways I&#8217;ve shown you above. But using a basic for loop is sometimes superior&#8212;especially if you want to be able to customize the code later (e.g., increasing the complexity of the loop body). <\/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=\"\">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 6\nt = []\nfor k, v in d.items(): t.append((k,v))\nprint(t)\n# [('Alice', 19), ('Bob', 23), ('Carl', 47)]\n<\/pre>\n<p>A <a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-a-simple-tutorial\/\" title=\"Python One Line For Loop [A Simple Tutorial]\" target=\"_blank\" rel=\"noreferrer noopener\">single-line for loop<\/a> or <a href=\"https:\/\/blog.finxter.com\/which-is-faster-list-comprehension-or-map-function-in-python\/\" title=\"Which is Faster: List Comprehension or Map Function in Python?\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehension<\/a> statement is not the most Pythonic way to convert a dictionary to a Python list if you want to modify each new list element using a more complicated body expression. In this case, a straightforward for loop is your best choice!<\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/list-to-dict-convert-a-list-into-a-dictionary-in-python\/\" title=\"List to Dict \u2014 Convert a List Into a Dictionary in Python\" target=\"_blank\" rel=\"noreferrer noopener\">List to Dict Conversion<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/how-to-convert-a-list-of-list-to-a-dictionary-in-python\/\" title=\"How to Convert a List of List to a Dictionary in Python?\" target=\"_blank\" rel=\"noreferrer noopener\">How to Convert a List of List to a Dictionary in Python?<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Dictionary \u2013 The Ultimate Guide\">Ultimate Guide to Dictionaries<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Lists\">Ultimate Guide to Lists<\/a><\/li>\n<\/ul>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<\/p>\n<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: To convert a dictionary to a list of tuples, use the dict.items() method to obtain an iterable of (key, value) pairs and convert it to a list using the list(&#8230;) constructor: list(dict.items()). To modify each key value pair before storing it in the list, you can use the list comprehension statement [(k&#8217;, v&#8217;) for [&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-114797","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\/114797","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=114797"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114797\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114797"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114797"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114797"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}