Map[K]V
Map[K]V
Section titled “Map[K]V”PyGo provides first-class support for generic map types using the Map[K, V] syntax. Maps are type-safe at compile time and mechanically transpiled to idiomatic Go map[K]V and Python dict[K, V] types.
Basic Usage
Section titled “Basic Usage”model Config: app_name: String settings: Map[String, String] # Map of string keys to string values thresholds: Map[String, Int] # Map of string keys to int valuesModel Values
Section titled “Model Values”model User: name: String
model Team: name: String members: Map[String, User] # Map of user IDs to User objectsNested Maps
Section titled “Nested Maps”model MultiTenantConfig: data: Map[String, Map[String, String]] # 2D map of stringsType Safety
Section titled “Type Safety”Maps are validated at compile time:
config = Config( app_name="MyApp", settings={"theme": "dark", "lang": "en"}, thresholds={"max_retries": 3, "timeout": 30})
# Valid — accessing a known key typetheme = config.settings["theme"]
# Invalid — the transpiler rejects this at compile time# config.settings[123] # Error: 123 is not StringGenerated Code
Section titled “Generated Code”Go:
type Config struct { AppName string Settings map[string]string Thresholds map[string]int}Python:
from typing import Dict
class Config(BaseModel): app_name: str settings: Dict[str, str] thresholds: Dict[str, int]Database Representation
Section titled “Database Representation”Maps are stored in the database as follows:
- SQLite: JSON-encoded as
TEXT - PostgreSQL:
JSONBcolumn type
CREATE TABLE config ( id INTEGER PRIMARY KEY, app_name TEXT NOT NULL, settings TEXT, -- JSON: {"theme": "dark", "lang": "en"} thresholds TEXT -- JSON: {"max_retries": 3, "timeout": 30});Map Operations
Section titled “Map Operations”PyGo supports the following operations on maps:
Insert/Update
Section titled “Insert/Update”config.settings["theme"] = "light"Get with Default
Section titled “Get with Default”theme = config.settings.get("theme", "dark")Delete
Section titled “Delete”del config.settings["theme"]Contains Check
Section titled “Contains Check”if "theme" in config.settings: print(config.settings["theme"])Keys / Values / Items
Section titled “Keys / Values / Items”keys = config.settings.keys() # ["theme", "lang"]values = config.settings.values() # ["light", "en"]items = config.settings.items() # [("theme", "light"), ("lang", "en")]Nullable Maps
Section titled “Nullable Maps”Use Map[K, V]? for nullable maps:
model Config: app_name: String settings: Map[String, String]? = None # Can be NULLBest Practices
Section titled “Best Practices”- Use
Map[String, String]for flexible key-value configuration - Use
Map[String, Model]for lookup tables and indexed collections - Use
Map[String, Map[String, V]]sparingly — consider flattening the structure - Always provide default empty maps to avoid
nullissues