5 Best Ways to Convert Python Dict to List of Pairs

πŸ’‘ Problem Formulation: Converting a Python dictionary into a list of pairs (tuples) is a common task when you need to pass data into functions that expect a list format, or when you want to perform operations that dictionaries don’t support directly. Given an input like {"a": 1, "b": 2}, the desired output would be [("a", 1), ("b", 2)]. This article explores several ways to achieve this transformation.

Method 1: Using a for loop

Converting a dictionary to a list of pairs with a for loop is intuitive and straightforward. This method iterates over the dictionary items, which returns key-value pairs, and appends them as tuples to a list. The function signature would be: dict_to_list_of_pairs(dict).

Here’s an example:

def dict_to_list_of_pairs(d):
    pairs_list = []
    for key, value in d.items():
        pairs_list.append((key, value))
    return pairs_list

# Example usage:
my_dict = {'apple': 3, 'banana': 5, 'cherry': 7}
print(dict_to_list_of_pairs(my_dict))

Output:

[('apple', 3), ('banana', 5), ('cherry', 7)]

This straightforward approach leverages the iterability of dictionaries in Python. By iterating through the items() of the dictionary, we receive key-value pairs that we can directly form into tuples and collect in a list. It’s a clear and beginner-friendly method.

Method 2: List Comprehension

List comprehension in Python provides a concise way to create lists. It consists of brackets containing an expression followed by a for clause. This expression gets evaluated for each element that the for loop iterates over. Here it’s used to generate a list of tuple pairs from a dictionary:

Here’s an example:

my_dict = {'python': 3.8, 'java': 14, 'ruby': 2.7}

pairs_list = [(k, v) for k, v in my_dict.items()]

print(pairs_list)

Output:

[('python', 3.8), ('java', 14), ('ruby', 2.7)]

This code snippet uses list comprehension to create a new list on the fly. It is a one-liner that replaces multiple lines from the previous method, making the code more compact and pythonic.

Method 3: Using the map() function

The map() function applies a given function to each item of an iterable (list, tuple, etc.) and returns a list of the results. In this case, the map() function can be used to convert each dictionary entry into a tuple, resulting in a list of tuples.

Here’s an example:

my_dict = {'cat': 'meow', 'dog': 'woof', 'fox': '???'}

pairs_list = list(map(lambda kv: (kv[0], kv[1]), my_dict.items()))

print(pairs_list)

Output:

[('cat', 'meow'), ('dog', 'woof'), ('fox', '???')]

In this snippet, map() is used with a lambda function that takes in key-value pairs and encapsulates them into tuples, then the whole map object is converted into a list.

Method 4: Using the *operator to Unpack the Dictionary

Python’s * operator can be used for unpacking iterables. With dictionaries, unpacking keys into a list can be done with *, and keys with their associated values by using **. To get a list of pairs, you’ll need a combination of unpacking and the items() method.

Here’s an example:

my_dict = {'gold': 50, 'silver': 70, 'bronze': 90}

pairs_list = [*my_dict.items()]

print(pairs_list)

Output:

[('gold', 50), ('silver', 70), ('bronze', 90)]

This snippet cleverly utilizes the unpacking operator * to convert the items() view into a list. Note that the items() method already returns key-value pairs, so the operator is effectively converting this view directly into a list.

Bonus One-Liner Method 5: Using the zip() function

Python’s zip() function is usually used to map the index of multiple containers so that they can be used just as a single entity. In this case, it can be used to zip the keys and values together, obtaining a list of tuples.

Here’s an example:

my_dict = {'January': 31, 'February': 28, 'March': 31}

pairs_list = list(zip(my_dict.keys(), my_dict.values()))

print(pairs_list)

Output:

[('January', 31), ('February', 28), ('March', 31)]

This method zips keys and values (retrieved separately using keys() and values() methods) into a list of tuples. This approach is also succinct and directly creates a list from the zip object.

Summary/Discussion

  • Method 1: Using a for loop. Clear and explicit. Slower on large dictionaries.
  • Method 2: List Comprehension. Concise. Preferred for its readability and simplicity.
  • Method 3: Using the map() function. Functional approach. Can be less readable to beginners.
  • Method 4: Unpacking with *. Clever and elegant. May be unfamiliar to those not used to unpacking.
  • Method 5: Using the zip() function. Compact one-liner. Requires understanding of zip() behavior.