The Wayback Machine - https://web.archive.org/web/20240916100957/https://www.geeksforgeeks.org/python-dict-of-tuples-to-json/
Open In App

Python – Dict of tuples to JSON

Last Updated : 28 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss how to convert a dictionary of tuples to JSON.

Method 1: Using json.dumps()

This will convert dictionary of tuples to json

Syntax: json.dumps(dictionary, indent)

Parameters:  

  • dictionary is the input dictionary.
  • indent specify the number of units of indentation

Example: Python dict of tuples to json conversion

Python3




# import json module
import json
  
# dictionary of employee data
data = {
    "id": ("1", "2", "3"),
    "name": ("bhanu", "sivanagulu"),
    "department": ("HR", "IT")
}
  
# convert into json
final = json.dumps(data, indent=2)
  
# display
print(final)


Output:

{
  "id": [
    "1",
    "2",
    "3"
  ],
  "name": [
    "bhanu",
    "sivanagulu"
  ],
  "department": [
    "HR",
    "IT"
  ]
}

Method 2: Using json.dump()

This will write converted json data into file, which will be downloaded and saved on your computer.

Syntax: json.dump(dictionary,pointer)

Parameters:  

  • dictionary is the input dictionary.
  • pointer is the file pointer that is  opened in write or append mode.

Syntax:

with open("mydata.json", "w") as final:
    json.dump(data, final)

where, mydata is the new JSON file

Finally , we have to download the created JSON file

Syntax:

files.download('mydata.json')

Example: Python dict of tuples to json conversion

Python3




# import json module
from google.colab import files
import json
  
# dictionary of employee data
data = {
    "id": ("1", "2", "3"),
    "name": ("bhanu", "sivanagulu"),
    "department": ("HR", "IT")
}
  
# convert into json
# file name is mydata
with open("mydata.json", "w") as final:
    json.dump(data, final)
  
# download the json file
files.download('mydata.json')


Output:



Similar Reads

Difference between dict.items() and dict.iteritems() in Python
dict.items() and dict.iteriteams() almost does the same thing, but there is a slight difference between them - dict.items(): returns a copy of the dictionary’s list in the form of (key, value) tuple pairs, which is a (Python v3.x) version, and exists in (Python v2.x) version.dict.iteritems(): returns an iterator of the dictionary’s list in the form
3 min read
Choosing dict.get() Over dict[] in Python
In Python, dictionaries are a fundamental data structure used to store key-value pairs. Accessing values in a dictionary using a key can be done in two primary ways: using the square bracket notation (dict[key]) or the get method (dict.get(key)). While both methods retrieve the value associated with the specified key, there are key differences betw
2 min read
How to use dict.get() with multidimensional dict?
The get() method in python returns the value for the key if the key is in the dictionary. If the key is not present in a dictionary it returns None. It also takes another optional parameter which is the value that will be returned if the key is not found in a dictionary. Syntax: dict.get(key, value) Here, the key is a must parameter which is a key
5 min read
Creating a Pandas DataFrame using Dict of Tuples in Python
Working with Python dictionaries containing tuples is a common scenario, especially when dealing with heterogeneous data. Transforming this data into a Pandas DataFrame allows for efficient manipulation and analysis. In this article, we will see how we can convert a dictionary with a tuple into a DataFrame in Python. Convert Dictionary with Tuple i
2 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Create a Pandas Dataframe from a dict of equal length lists
Given a dictionary of equal length lists, task is to create a Pandas DataFrame from it. There are various ways of creating a DataFrame in Pandas. One way is to convert a dictionary containing lists of equal lengths as values. Let's discuss how to create a Pandas Dataframe from a dict of equal length lists with help of examples. Example #1: Given a
2 min read
Python | Creating DataFrame from dict of narray/lists
As we know Pandas is all-time great tools for data analysis. One of the most important data type is dataframe. It is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe
2 min read
enchant.Dict() in Python
Enchant is a module in python which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in dictionary or not. enchant.Dict() enchant.Dict() is an inbuilt method of enchant module. It is used to create a Dict object, which is the most important object
2 min read
Python - Convert dict of list to Pandas dataframe
In this article, we will discuss how to convert a dictionary of lists to a pandas dataframe. Method 1: Using DataFrame.from_dict() We will use the from_dict method. This method will construct DataFrame from dict of array-like or dicts. Syntax: pandas.DataFrame.from_dict(dictionary) where dictionary is the input dictionary Example: Program to take s
2 min read
How to Access dict Attribute in Python
In Python, A dictionary is a type of data structure that may be used to hold collections of key-value pairs. A dictionary's keys are connected with specific values, and you can access these values by using the keys. When working with dictionaries, accessing dictionary attributes is a basic function because it allows you to retrieve and modify the d
6 min read
Python dict() Function
A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. A dictionary is an indexed data structure i.e. the contents of a dictionary can be accessed by using indexes, here in the dictionary, the key is used as an index. Here, the dict() function is used to create a new dictionary or convert other iterable objects in
4 min read
How to Change a Django QueryDict to Python Dict
In Django, a QueryDict is a specialized dictionary that handles HTTP GET and POST parameters. In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict. There are instances when we may need to convert the QueryDict into a regular Python dictionary dict() to perform various operations. QueryDict is a subclass of di
6 min read
Mapping a Python Dict to a Polars Series
Polars is an efficient DataFrame library that excels in performance, especially when working with large datasets. While manipulating data, you might encounter situations where you need to map the values of a column based on a Python dictionary. This is a common task when you want to replace or map values in a column based on some predefined logic.
3 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different methods, each offering its own advantages in differen
3 min read
How to convert a nested OrderedDict to dict?
In this article, we will discuss how to convert a nested OrderedDict to dict? Before this we must go through some concepts: Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value i
3 min read
Sqlalchemy core, insert multiple rows from a tuple instead of dict
SQLAlchemy is a popular Python library used for working with databases. SQLAlchemy provides an Object-Relational Mapping (ORM) layer and a Core layer. The ORM layer allows developers to work with databases using Python objects, while the Core layer provides a lower-level interface for SQL-oriented database work. In this article, we'll explore how t
3 min read
How to fix "Error: 'dict' object has no attribute 'iteritems'
The Error: " 'dict' object has no attribute 'iteritems'” occurs in Python 3.x because the iteritems() method, which was used in Python 2.x to iterate over dictionary items, was removed in Python 3.x. In Python 3.x, we use the items() method instead. This article will explain the causes of this error and provide methods to fix it. What is “Error: di
2 min read
Convert Django Model Object to Dict with all of the Fields Intact
Django, a high-level Python web framework, simplifies the process of building web applications by providing a robust ORM (Object-Relational Mapping) system. Often, while developing web applications, there arises a need to convert Django model instances into dictionaries, retaining all the fields intact. This conversion is useful for various purpose
4 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Tuples in Python
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable. Creating Python TuplesThere are various ways by which you can create a tuple i
6 min read
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] E
3 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Python | Remove empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Filter dictionary of tuples by condition
Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using items
3 min read
Python | Unzip a list of tuples
The zipping technique, that is assigning a key value or pairing from two different lists has been covered in many articles before, sometimes we have a specific utility to perform the reverse task. This task can be achieved by various methods. Let's discuss some of the methods to unzip a list of tuples. Method #1: Using List comprehension Using list
5 min read
Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Article Tags :
Practice Tags :