×

Dictionary to JSON Python

  • In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.
  • We can use many built-in packages which arenamedJSON.
  • Before using the packages, we have to import the package in python.
  • Let us consider an example program:
# import thejson packing
import json      
# Data to write  
dictionary ={ 
  "id": "02", 
  "name": "vijay", 
  "department": "Cr"
} 
      
# Serializing json  
json_obj = json.dumps(dictionary, indent = 2) 
print(json_obj)

Output:

“id”: “02”,
“name”: “vijay”,
 “department”: “CR”

Consider a program to convert a nested dictionary to JSON python:

# import thejson packing
import json
# data to be written
dictionary = {
 "fruit":{"guava": "1","color": "green"},
"vegetable": {"tomato": "2","color": "red"},
}
# using the json
d = json.dumps(dictionary)
print(d)

Output:

"fruit":
{"guava": "1","color": "green"},
"vegetable":
 {"tomato": "2","color": "red"}
  • In the above program, a module is imported. And we consider two different variables, fruits, and vegetables, Which are considered dictionaries.
  • A variable d is used. In which the json.dumps( ) function is used to store the dictionary.

Dictionary to JSON File Python

  • Let us consider an example program to convert a dictionary to json file in python.
# importing json packing
import json
st = {"Name": "Kumari","Age": 16,"hobby":"reading"}
with open('student.json', 'w') as f:
json.dump(st, f)

Output:

“name”: “kumari”,
“age”: 16,
“hobby”: “reading”
  • In the above program, we used a JSON module and used a student dictionary to open the file.
  • The name of the file is student.json, and ‘w’ is used to write the file.
  • The student.json file is stored in the dictionary the json.dump( ) module is used.

Converting Dictionary to JSON File in Python

  • Let us consider an example program to convert dictionary to json file in python.
# import thejson packing
import json
class fruit(dict):
    def __str__(self):
        return json.dumps(self)
c = [[‘apple’,'banana']]
q= fruit(combo)
print(q)

Output:

 “apple”: “orange”
  • In the above code, the JSON module is used.
  • The method__str__(self)  is used in the representation of the string.
  • Here we also declared the c and q variables where q is assigned to the class.
  • The parameter c is used to obtain the output.

Dictionary to JSON Array Python

  • Let us consider an example program to convert a dictionary to a JSON array in python.
# import thejson packing
import json
dic = {'lion': 3, 'tiger': 1}
arr = [ {'key': i, 'value': dic[k]} for i in dic]
print(json.dumps(arr))

Output:

{ “key”: “ lion “, “value ”: 3},
{ “key”: “ tiger “, “value”: 1}
  • In the above code, the JSON module is used.
  • Here the dic is a variable with assigned key-value pair.
  • The arr variable is used to declare the array, which can be used to check what is key and what is value.
  • The file is stored in the dictionary, the json.dump( ) module is used.
  • The loop is useful for storing of the value.

Multiple Dictionaries to JSON Python

  • Let us consider an example program to convert multiple dictionary to json file in python.
# import the json packing
import json
dict = {"fruit":{"mango": "1","color": "yellow"},"vegetable": {"onion": "4","white": "red"},"chocolate":{"dairy milk":"2","color":"black"}}
report = json.dumps(dict)
print(report)

Output:

{"fruit":{"mango": "1","color”: "yellow"},"vegetable": {"onion": "4","white": "red"},"chocolate":{"dairy milk":"2","color":"black"}}
  • In the above code, the JSON module is used. And a variable dict is declared.
  • We used json.dumps ( ) module to store the data in the dictionary.

Dictionary to JSON Using the Sort_keys in Python

  • Let us consider an example program to convert a dictionary to json file using sort_keysin python.
# import thejson packing
import json
dictionary ={"Name": "rushi", "Branch": " ECE ", "CGPA": " 8.0"} 
d = json.dumps(dict, indent = 5, sort_keys = True) 
print(d)

Output:

" Branch ": " ECE ",
" CGPA ": " 8.0"
" Name ": " rushi ", 
  • In the above code, the JSON module is used.
  • Here the dic is a variable with assigned key-value pair.
  • We used json.dumps module to store the values.
  • The sort_keys is TRUE, which is used to sort the values in thedictionary. If the value is false then the values will not be sorted.

Related Topics

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.