Skip to content
Related Articles

Related Articles

Python – Dict of tuples to JSON

Improve Article
Save Article
Like Article
  • Last Updated : 28 Nov, 2021

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:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!