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"}
CodePudding user response:
I'm not sure what your motivation is, but the only time I want this is when I want my dictionary to be copy/pastable for JSON files. It turns out the json module happens to do both in your case:
import json
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",
}
print(json.dumps(movie_data(movie_list)))
# {"name": "Marvel", "movies": {"spiderman": "Tom", "Thor": "Chris"}, "Review": "5star"}
CodePudding user response:
Try using json package.
import json
a = movie_data(movie_list)
print(json.dumps(a))
CodePudding user response:
Python uses single quotes or double quotes for strings : "abc" == 'abc'.
By default, print will display single quotes, unless the string already contains quotes :
>>> "123"
'123'
>>> d = {'a': "b"}
>>> print(d)
{'a': 'b'}
>>> d
{'a': 'b'}
So those outputs are equal. The difference comes from Python's print function.
>>> a = {'name': 'Marvel', 'movies': {'spiderman': 'Tom', 'Thor': 'Chris'}, 'Review': '5star'}
>>> b = {"name":"Marvel","movies": {"spiderman":"Tom","Thor":"Chris"},"Review":"5star"}
>>> a == b
True
CodePudding user response:
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:
- get the string that will get printed
- 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"}
