Python tuple from dictionary

Python: Convert dictionary to list of tuples/ pairs

In this article, we will discuss different ways to convert all key-value pairs of a dictionary to a list of tuples.

Table of Contents

Convert all pairs of dictionary to list of tuples using items()

In Python, dictionary class provides a function items(), which returns an iterable sequence (dict_items) of all key-value pairs of the dictionary. This retuned sequence is a view of the actual key-value pairs in the dictionary. We can use pass this iterable sequence to the list() function to get a list of tuples. For example,

# Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, "why": 89, "Hi": 51, "How": 79 ># Convert all key-value pairs of dict to list of tuples list_of_tuples = list(word_freq.items()) print(list_of_tuples)
[('Hello', 56), ('at', 23), ('test', 43), ('this', 78), ('why', 89), ('Hi', 51), ('How', 79)]

We converted all key-value pairs of a dictionary to a list of tuples.

Читайте также:  Async with outside async function python

Frequently Asked:

Use zip() to convert all pairs of dictionary to list of tuples

In Python, the zip() function accepts multiple iterable sequences as argument and returns a merged sequence. In the returned sequence element at ith position is a tuple containing items at ith position of passed sequences.

  • dict.keys(): Returns an iterable sequence of all keys of dictionary
  • dict.values(): Returns an iterable sequence of all values of dictionary

Then we can pass these two sequences (keys and values ) to the zip() function and it will create a list of tuples, where ith tuple in list will contain the ith key and ith value of the dictionary. For example,

# Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, "why": 89, "Hi": 51, "How": 79 ># Convert all key-value pairs of dict to list of tuples list_of_tuples = list(zip(word_freq.keys(), word_freq.values())) print(list_of_tuples)
[('Hello', 56), ('at', 23), ('test', 43), ('this', 78), ('why', 89), ('Hi', 51), ('How', 79)]

We converted all key-value pairs of a dictionary to a list of tuples.

Use List comprehension to convert all pairs of dictionary to list of tuples

dict.items() returns an iterable sequence of all key-value pairs of dictionary. We can iterate over this sequence using a list comprehension and build a list of tuples. In this list of tuple the ith tuple contains the ith key-value pair of dictionary. For example,

# Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, "why": 89, "Hi": 51, "How": 79 ># Convert all key-value pairs of dict to list of tuples list_of_tuples = [ (key, value) for key, value in word_freq.items()] print(list_of_tuples)
[('Hello', 56), ('at', 23), ('test', 43), ('this', 78), ('why', 89), ('Hi', 51), ('How', 79)]

We converted all key-value pairs of a dictionary to a list of tuples.

Use for-loop to convert all pairs of dictionary to list of tuples

We can create an empty list of tuples and then iterate over all-key pairs of dictionary using a for loop and add each key-value pair one by one to the list. For example,

# Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, "why": 89, "Hi": 51, "How": 79 ># Create empty list list_of_tuples = [] # Add all key-value pairs of dict to list of tuples for key in word_freq: list_of_tuples.append((key, word_freqPython tuple from dictionary)) print(list_of_tuples)
[('Hello', 56), ('at', 23), ('test', 43), ('this', 78), ('why', 89), ('Hi', 51), ('How', 79)]

We converted all key-value pairs of a dictionary to a list of tuples.

Convert selected pairs of dict to list of tuples in Python

In all the previous examples, we converted all key-value pairs of dictionary to a list of tuples. But what if we want to select only few pairs from dictionary based on a condition and convert them to list of tuples.

For example, select key-value pairs from dictionary where value is greater than 50 and convert them to a list,

# Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, "why": 89, "Hi": 51, "How": 79 ># Select pairs from dictionary whose value is greater than 50 # Convert these pairs to list of tuples list_of_tuples = [ (key, value) for key, value in word_freq.items() if value > 50] print(list_of_tuples)
[('Hello', 56), ('this', 78), ('why', 89), ('Hi', 51), ('How', 79)]

We converted only a few pairs of dictionary to a list of tuples.

We learned about different ways to convert key-value pairs of dictionary to a list of tuples.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Python: Convert a Dictionary to a List of Tuples (4 Easy Ways)

Python Convert Dictionary to List of Tuples Cover Image

In this tutorial, you’ll learn how to use Python to convert a dictionary into a list of tuples. You’ll learn how to do this using the list() function, Python list comprehensions, and the zip() function.

Knowing how to work with dictionaries and how to safely convert them to other Python data structures is an incredibly useful skill for any beginner or advanced Pythonista.

The Quick Answer: Use the list() function

Quick Answer - Python Convert Dictionary to List of Tuples

Convert a Python Dictionary to a List of Tuples Using the List Function

One of the most straightforward and Pythonic ways to convert a Python dictionary into a list of tuples is to the use the built-in list() function. This function takes an object and generates a list with its items.

One of the built-in methods for dictionaries is the .items() methods, which returns a tuple of tuples of the key value pairs found inside the dictionary. We can use this method and pass it into the list() function, in order to generate a list of tuples that contain the key value pairs from our dictionary.

# Convert a Dictionary into a List of Tuples Using list() sample_dict = list_of_tuples = list(sample_dict.items()) print(list_of_tuples) # Returns: [('john', 30), ('nik', 32), ('datagy', 40)]

We can see here that we passed our dictionaries items into the list() function. This returned a list of tuples, with corresponding key-value pairs.

In the next section, you’ll learn how to use a Python list comprehension to convert a dict into a list of tuples.

Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.

Convert a Python Dictionary to a List of Tuples Using a List Comprehension

Python list comprehensions are elegant ways in which to generate lists based on another iterable object. In order to convert a dictionary in Python to a list of tuples, we will loop over the keys and values and generate tuples.

Let’s take a look at what this code looks like:

# Convert a Dictionary into a List of Tuples Using a List Comprehension sample_dict = list_of_tuples = [(key, value) for key, value in sample_dict.items()] print(list_of_tuples) # Returns: [('john', 30), ('nik', 32), ('datagy', 40)]

Let’s break down our list comprehension a little bit:

  1. Our iterable is represented by the sample_dict.items() , which returns a tuple of tuples of our key value pairs
  2. We iterate over these by creating a new tuple of the key-value pairs

In the next section, you’ll learn how to use the Python zip() function to convert a dict to a list of tuples.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Convert a Python Dictionary to a List of Tuples Using the Zip Function

The Python zip() function allows you to iterate in sequence over multiple iterative objects. We can create two iterative objects for a dictionary’s keys and values by using the .keys() and .items() methods. Both of these returns iterable objects, containing either the keys or the values of our dictionary.

Let’s take a look at how we can do this in Python:

# Convert a Dictionary into a List of Tuples Using the Zip Function sample_dict = keys = sample_dict.keys() values = sample_dict.values() list_of_tuples = list(zip(keys, values)) print(list_of_tuples) # Returns: [('john', 30), ('nik', 32), ('datagy', 40)]

Let’s take a look at what we’ve done here:

  1. We loaded our sample dictionary
  2. We created two new objects, one containing the keys and one containing the values
  3. We used the zip() function to combine these two objects together, in sequence
  4. We converted it to a list of tuples

In the next section, you’ll learn how to use the collections library to convert a dict to a list of tuples.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Convert a Python Dictionary to a List of Tuples Using a For Loop

A very intuitive way to accomplish converting a Python dict to a list of tuples is to use a Python for loop.

Python for-loops allow us to easily iterate over a sequence and perform a provided action as a result.

Let’s take a look at how we can accomplish this, using a Python for loop:

# Convert a Dictionary into a List of Tuples Using a for loop sample_dict = list_of_tuples = list() for key in sample_dict: list_of_tuples.append((key, sample_dict.get('key'))) print(list_of_tuples) # Returns: [('john', 30), ('nik', 32), ('datagy', 40)]

Let’s explore this code a little bit to better understand what is going on:

  1. We generated an empty list, to which we will append our tuples
  2. We loop over each key in the sample_dict object
  3. We append a tuple containing the key and the value that the key returns using the .get() method

Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

Conclusion

In this post, you learned how to use Python to convert a dictionary to a list of tuples. Being able to convert and move between different Python data structures is an incredibly useful skill to learn. You learned how to do this using the list() function, Python list comprehensions, and the zip() function

To learn more about the Python collections library, check out the official documentation here.

Источник

Оцените статью