Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Dict to List — How to Convert a Dictionary to a List in Python
1
Dict to List — How to Convert a Dictionary to a List in Python

Summary: To convert a dictionary to a list of tuples, use the
Code:
dict.items()
method to obtain an iterable of
Code:
(key, value)
pairs and convert it to a list using the
Code:
list(...)
constructor:
Code:
list(dict.items())
. 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()]
replacing
Code:
k'
and
Code:
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, you’ll learn the most Pythonic way to convert a dictionaryto a list.



Problem: Given a dictionary of
Code:
key:value
pairs. Convert it to a list of
Code:
(key, value)
tuples.

Example: Given the following dictionary.

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

You want to convert it to a list of
Code:
(key, value)
tuples:

Code:
[('Alice', 19), ('Bob', 23), ('Carl', 47)]

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

https://trinket.io/embed/python/63517365f5

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

Let’s dive into the methods!

Method 1: List of Tuples with dict.items() + list()

[Image: dict_to_lists-1024x576.jpg]

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

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

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

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

Using the
Code:
items()
method on the dictionary object is the most Pythonic way if everything you want is to retrieve a list of
Code:
(key, value)
pairs. However, what if you want to get a list of keys—ignoring the values for now?

Method 2: List of Keys with dict.key()

To get a list of key values, use the
Code:
dict.keys()
method and pass the resulting iterable into a
Code:
list()
constructor.

Code:
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
Code:
dict.values()
method and pass the resulting iterable into a
Code:
list()
constructor.

Code:
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
Code:
(key, value)
tuple? Let’s study some alternatives.

Method 4: List Comprehension with dict.items()

List comprehension is a compact way of creating lists. The simple formula is
Code:
[expression + context]
.
  • Expression: What to do with each list element?

  • Context: What elements to select? The context consists of an arbitrary number of
    Code:
    for
    and
    Code:
    if
    statements.

You can use list comprehension to modify each
Code:
(key, value)
pair from the original dictionary before you store the result in the new list.

Code:
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 slicingand reduce each value by one.

Method 5: zip() with dict.keys() and dict.values()

Just for comprehensibility, you could (theoretically) use the
Code:
zip()
function
to create a list of tuples:

Code:
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, there’s no benefit compared to just using the
Code:
dict.items()
method. However, I wanted to show you this because the
Code:
zip()
function is frequently used in Python and it’s important for you to understand it.

Method 6: Basic Loop

The last method uses a basic for loop—not the worst way of doing it! Sure, a Python pro would use the most Pythonic ways I’ve shown you above. But using a basic for loop is sometimes superior—especially if you want to be able to customize the code later (e.g., increasing the complexity of the loop body).

Code:
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:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even 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, too—from the comfort of your own home.

Join the free webinar now!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: