Dict from list Python

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[...] constructor: list[dict.items[]]. To modify each key value pair before storing it in the list, you can use the list comprehension statement [[k', v'] for k, v in dict.items[]] replacing k' and v' with your specific modifications.

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, youll learn the most Pythonic way to convert a dictionary to a list.

Problem: Given a dictionary of key:value pairs. Convert it to a list of [key, value] tuples.

Example: Given the following dictionary.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47}

You want to convert it to a list of [key, value] tuples:

[['Alice', 19], ['Bob', 23], ['Carl', 47]]

You can get a quick overview of the methods examined in this article next:

Exercise: Change the data structure of the dictionary elements. Does it still work?

Lets dive into the methods!

Table of Contents

  • Method 1: List of Tuples with dict.items[] + list[]
  • Method 2: List of Keys with dict.key[]
  • Method 3: List of Values with dict.values[]
  • Method 4: List Comprehension with dict.items[]
  • Method 5: zip[] with dict.keys[] and dict.values[]
  • Method 6: Basic Loop
  • Where to Go From Here?

Method 1: List of Tuples with dict.items[] + list[]

The first approach uses the dictionary method dict.items[] to retrieve an iterable of [key, value] tuples. The only thing left is to convert it to a list using the built-in list[] constructor.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 1 t = list[d.items[]] print[t] # [['Alice', 19], ['Bob', 23], ['Carl', 47]]

The variable t now holds a list of [key, value] tuples. Note that in many cases, its 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 [key, value] pairs in the dictionary, you can do so without conversion:

for k,v in d.items[]: s = str[k] + '->' + str[v] print[s] ''' Alice->19 Bob->23 Carl->47 '''

Using the items[] method on the dictionary object is the most Pythonic way if everything you want is to retrieve a list of [key, value] pairs. However, what if you want to get a list of keysignoring the values for now?

Method 2: List of Keys with dict.key[]

To get a list of key values, use the dict.keys[] method and pass the resulting iterable into a list[] constructor.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 2 t = list[d.keys[]] print[t] # ['Alice', 'Bob', 'Carl']

Similarly, you may want to get a list of values.

Method 3: List of Values with dict.values[]

To get a list of key values, use the dict.values[] method and pass the resulting iterable into a list[] constructor.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 3 t = list[d.values[]] print[t] # [19, 23, 47]

But what if you want to modify each [key, value] tuple? Lets study some alternatives.

Method 4: List Comprehension with dict.items[]

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

You can use list comprehension to modify each [key, value] pair from the original dictionary before you store the result in the new list.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 4 t = [[k[:3], v-1] for k, v in d.items[]] print[t] # [['Ali', 18], ['Bob', 22], ['Car', 46]]

You transform each key to a string with three characters using slicing and reduce each value by one.

Method 5: zip[] with dict.keys[] and dict.values[]

Just for comprehensibility, you could [theoretically] use the zip[] function to create a list of tuples:

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 5 t = list[zip[d.keys[], d.values[]]] print[t] # [['Alice', 19], ['Bob', 23], ['Carl', 47]]

However, theres no benefit compared to just using the dict.items[] method. However, I wanted to show you this because the zip[] function is frequently used in Python and its important for you to understand it.

Method 6: Basic Loop

The last method uses a basic for loopnot the worst way of doing it! Sure, a Python pro would use the most Pythonic ways Ive shown you above. But using a basic for loop is sometimes superiorespecially if you want to be able to customize the code later [e.g., increasing the complexity of the loop body].

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 6 t = [] for k, v in d.items[]: t.append[[k,v]] print[t] # [['Alice', 19], ['Bob', 23], ['Carl', 47]]

A single-line for loop or list comprehension 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!

Related articles:

  • List to Dict Conversion
  • How to Convert a List of List to a Dictionary in Python?
  • Ultimate Guide to Dictionaries
  • Ultimate Guide to Lists

Where to Go From Here?

Enough theory. Lets get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. Thats how you polish the skills you really need in practice. After all, whats the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! Its the best way of approaching the task of improving your Python skillseven if you are a complete beginner.

Join my free webinar How to Build Your High-Income Skill Python and watch how I grew my coding business online and how you can, toofrom the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. Hes author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Video liên quan

Chủ Đề