Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python, How to replace single quotes to double quotes

I was giving input in double quotes, after processing some operations need to display output in double quotes where its giving in single quote format

code:

def movie_data(movie_list):
    mve = {}
    for k, v in movie_list.items():
        if type(v) == str:
            mve[k] = str(v) if v else None
        elif type(v) == dict:
            mve[k] = movie_data(v)
        else:
            pass
    return mve
movie_list = {"name":"Marvel","movies": {"spiderman":"Tom","Thor":"Chris"},"Review":"5star"}
movie_data(movie_list)

Output:

{'name': 'Marvel', 'movies': {'spiderman': 'Tom', 'Thor': 'Chris'}, 'Review': '5star'}

Expected Output:

{"name":"Marvel","movies": {"spiderman":"Tom","Thor":"Chris"},"Review":"5star"}
like image 447
user10389226 Avatar asked Jul 23 '26 03:07

user10389226


1 Answers

If you print a dictionary, it will use the dictionary method __str__ to convert the dictionary to a printable string. The __str__ method is the one using single quotes.

movie_list = {"name":"Marvel","movies": {"spiderman":"Tom","Thor":"Chris"},"Review":"5star"}
print(movie_list.__str__())

What you can do to get double quotes is to:

  1. get the string that will get printed
  2. replace the double quotes by single quotes

Here's the code to do it:

movie_list = {"name":"Marvel","movies": {"spiderman":"Tom","Thor":"Chris"},"Review":"5star"}
movie_list_str = movie_list.__str__().replace("'", '"')
print(movie_list_str)

And the output is:

{"name": "Marvel", "movies": {"spiderman": "Tom", "Thor": "Chris"}, "Review": "5star"}
like image 138
groumache Avatar answered Jul 24 '26 18:07

groumache



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!