We will use json.dums() function to convert to json from python dictionary and json.loads() to convert from json to python dictionary.
In this example code we used flower details data in python dictionary and converted it to json.
import json
# flowers in python dictionary
flowers = {
"rose": {
"scientific_name": "Rosa",
"grows_in": ["gardens", "wild"],
"colors": ["red", "pink", "white"]
},
"sunflower": {
"scientific_name": "Helianthus annuus",
"grows_in": ["fields", "gardens"],
"colors": ["yellow"]
}
}
# Converting Python dictionary to JSON
flowers_json = json.dumps(flowers)
# converted to json
print(flowers_json)
# we can add indent to make it more readable
flowers_json = json.dumps(flowers, indent=4)
print(flowers_json)
# Now convert json to python dictionary
#fowers_json is alreay in json
flowers_dict = json.loads(flowers_json)
#converted to python dictionary
print(flowers_dict)
Exporting Python Dictionaries to JSON Files
we can also export this python dictionary data to json
import json
# flowers in python dictionary
flowers = {
"rose": {
"scientific_name": "Rosa",
"grows_in": ["gardens", "wild"],
"colors": ["red", "pink", "white"]
},
"sunflower": {
"scientific_name": "Helianthus annuus",
"grows_in": ["fields", "gardens"],
"colors": ["yellow"]
}
}
# Converting Python dictionary to JSON
flowers_json = json.dumps(flowers)
# Exporting Python dictionary to a JSON file
with open("flowers.json", "w") as json_file:
json.dump(flowers, json_file, indent=4)
Loading JSON Data from Files into Python Dictionaries
# Loading JSON data from a file into Python dictionary
import json
with open("flowers.json", "r") as json_file:
#convert to python dictionary with json.load()
loaded_flowers_dictionary = json.load(json_file)
print(loaded_flowers_dictionary)
Its a plain text format which comes from (Comma Separated Values)
Most spreadsheet application supports this. You can open and edit it from excl, Libra office cal , google sheets and other spread sheet application, also supported by most of the programming language.
For simplicity and flexibility often used in data science.
Create Our first csv file
We will create our csv file with as simple way as possible. Even we will not use any spreadsheet application.
Open any text editor. You can open vs code or geany or your beloved code editor.
In the text editor. create and save a new file named colors.cvs Make sure you properly added the .csv extinction.
The csv.reader function turns each row of the CSV file into a list of individual values. The example
import csv
with open('colors.csv', 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader)
for row in reader:
print(row)
color_name = row[0]
red_value = int(row[1])
green_value = int(row[2])
blue_value = int(row[3])
hex_code = row[4]
# We can now process the color data as needed
print(f"Color: {color_name} (R: {red_value}, G: {green_value}, B: {blue_value}), Hex Code: {hex_code}")
csv.DictReader
The csv.DictReader function turns each row of the CSV file into a dictionary, using the first row as keys (headers). Example:
import sys
import pygame
import matplotlib
from pygame.locals import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
This code imports a tool from Matplotlib that lets you save plots as image files (like PNG or JPG). Use this for embedding plots in websites, reports, or presentations. We will apply this to implement in pygame.
we will use pygame.time.Clock() to control the frame rate of this application
Create a Matplotlib figure and canvas
figure, axis = plt.subplots()
axis.plot([1, 2, 3, 4, 5, 6, 7], [10, 20, 25, 30, 25, 45, 50])
plot_canvas = FigureCanvas(figure) # Create a canvas to render the Matplotlib plot
figure, axis = plt.subplots() This sets up your plotting area. Imagine fig as a picture frame, and axis as the place inside it for our graph.
axis.plot([1, 2, 3, …], [10, 20, 25, …]) This draws the line. The numbers are coordinates (like on a map) for the line’s points.
plot_canvas = FigureCanvas(figure) This line gets our plot ready to be turned into an image file if needed.”
Apply the drawing and update in the while loop
# Main game loop
running = True
while running:
clock.tick(10)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
display_screen.fill(background_color)
# Draw the Matplotlib plot onto the Pygame screen
plot_canvas.draw() # Update the Matplotlib plot if needed
renderer = plot_canvas.get_renderer()
matplotlib_plot_rgba_image_data = renderer.tostring_rgb() # Get raw image data of the plot
plot_canvas_width, plot_canvas_height = plot_canvas.get_width_height()
# Convert the Matplotlib image data into a Pygame surface
plot_surface = pygame.image.fromstring(matplotlib_plot_rgba_image_data,
(plot_canvas_width, plot_canvas_height),
"RGB")
# Display the plot on the Pygame screen
display_screen.blit(plot_surface, (300, 50)) # Place the plot at position (300, 50)
pygame.display.update()
The complete Code
import sys
import pygame
import matplotlib
from pygame.locals import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
# Initialize Pygame
pygame.init()
# Set up the display window
clock = pygame.time.Clock() # Used to control the speed of the game loop
display_screen = pygame.display.set_mode((1200, 600)) # Create a window 1200 pixels wide, 600 pixels tall
background_color = (144, 238, 144) # A light green color
# Create the Matplotlib plot
figure, axis = plt.subplots() # Create a figure (the container) and an axis (for plotting)
axis.plot([1, 2, 3, 4, 5, 6, 7], [10, 20, 25, 30, 25, 45, 50]) # Plot sample data
plot_canvas = FigureCanvas(figure) # Create a canvas to render the Matplotlib plot
# Main game loop
running = True
while running:
clock.tick(10) # Limit the loop to run 10 times per second
# Handle events (like keyboard presses, mouse clicks)
for event in pygame.event.get():
if event.type == QUIT: # Check if the user clicked the close button
pygame.quit()
sys.exit()
# Clear the screen with the background color
display_screen.fill(background_color)
# Draw the Matplotlib plot onto the Pygame screen
plot_canvas.draw() # Update the Matplotlib plot if needed
renderer = plot_canvas.get_renderer()
matplotlib_plot_rgba_image_data = renderer.tostring_rgb() # Get raw image data of the plot
plot_canvas_width, plot_canvas_height = plot_canvas.get_width_height()
# Convert the Matplotlib image data into a Pygame surface
plot_surface = pygame.image.fromstring(matplotlib_plot_rgba_image_data,
(plot_canvas_width, plot_canvas_height),
"RGB")
# Display the plot on the Pygame screen
display_screen.blit(plot_surface, (300, 50)) # Place the plot at position (300, 50)
# Update the display to show changes
pygame.display.update()