Python Dictionary vs JSON
Let's learn the Difference Between dictionary and JSON
If you’ve ever worked with Python web frameworks like FastAPI or Django, you’ve likely seen how often dict
and JSON are used interchangeably. At first glance, they look almost identical—but they’re not the same.
In this post, we’ll clearly explain the differences between a Python dictionary and a JSON object, when to use each, and how to convert between them effectively.
Definitions
Aspect | Python Dictionary | JSON (JavaScript Object Notation) |
---|---|---|
Language Type | Native Python object | String-based data format |
Syntax | {'key': 'value'} | {"key": "value"} |
Key Differences
String Representation
A Pythondict
is an actual data structure in memory, whileJSON
is just a text string.Quotation Marks
Python allows both single and double quotes, but JSON strictly requires double quotes around keys and string values.
1
2
3
4
5
6
7
8
data = {'name': 'DS2Man', 'age': 30}
print(type(data)) # <class 'dict'>
print(data) # {'name': 'DS2Man', 'age': 30} # Note. single or double quotation
import json
dict2json = json.dumps(data)
print(type(dict2json)) # <class 'str'>
print(dict2json) # {"name": "DS2Man", "age": 30} # Note. must double quotation
How to Convert Between Them
Convert dict to JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
import json
data = {'name': 'DS2Man, 데투남', 'age': 30}
print(type(data)) # <class 'dict'>
print(data) # {'name': 'DS2Man, 데투남', 'age': 30} # Note. single or double
dict2json = json.dumps(data) # default : ensure_ascii=True
print(type(dict2json)) # <class 'str'>
print(dict2json) # {"name": "DS2Man, \ub370\ud22c\ub0a8", "age": 30} # Note. must double
dict2json = json.dumps(data, ensure_ascii=False)
print(type(dict2json)) # <class 'str'>
print(dict2json) # {"name": "DS2Man, 데투남", "age": 30} # Note. must double
You can use the ensure_ascii
option to convert Unicode characters into ASCII representations.
Option | Description |
---|---|
ensure_ascii=True (default) | Escapes all non-ASCII (Unicode) characters into ASCII (e.g., “한글” → \ud55c\uae00 ) |
ensure_ascii=False | Outputs Unicode characters as-is without escaping (e.g., “한글” → 한글 ) |
Convert JSON to dict
1
2
3
4
5
import json
json2dict = json.loads(dict2json)
print(type(json2dict)) # <class 'dict'>
print(json2dict) # {'name': 'Alice', 'age': 30}