Junior — Middle
How does using a dictionary differ from working with JSON format when handling data?
sobes.tech AI
Answer from AI
Dictionary (dict) in Python is a data structure that stores key-value pairs and is used within programs for convenient data access and modification. JSON (JavaScript Object Notation) is a text data exchange format used for serialization and data transfer between systems.
Main differences:
- Type: dictionary is an object in Python memory, JSON is a string in a specific format.
- Usage: dictionaries are convenient for working in code, JSON is used for data transfer over networks or saving to files.
- Conversion: Python uses
jsonmodules for serialization (json.dumps()) and deserialization (json.loads()) when working with JSON.
Example:
import json
# Python dictionary
data = {'name': 'Ivan', 'age': 30}
# Convert dictionary to JSON string
json_str = json.dumps(data, ensure_ascii=False)
print(json_str) # {"name": "Ivan", "age": 30}
# Reverse conversion
data_back = json.loads(json_str)
print(data_back['name']) # Ivan