forked from mouredev/Hello-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdicts_utils.py
More file actions
94 lines (71 loc) · 2.71 KB
/
dicts_utils.py
File metadata and controls
94 lines (71 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""
Utilidades puras para trabajar con diccionarios (Clase 07 — Dicts).
- Enfoque funcional: NO mutamos los dicts de entrada; devolvemos nuevos dicts.
- Validamos tipos para feedback claro.
Ejemplos rápidos:
>>> create_dict_from_pairs([("a", 1), ("b", 2)])
{'a': 1, 'b': 2}
>>> set_item({"a": 1}, "b", 2)
{'a': 1, 'b': 2}
>>> remove({"a": 1, "b": 2}, "a")
({'b': 2}, 1)
"""
from typing import Any, Dict, Iterable, List, Tuple
def _ensure_dict(d: Any) -> Dict[Any, Any]:
if not isinstance(d, dict):
raise ValueError("Se esperaba un dict como primer argumento")
return d # type: ignore[return-value]
def create_dict_from_pairs(pairs: Iterable[Tuple[Any, Any]]) -> Dict[Any, Any]:
"""Crea un dict a partir de una secuencia de pares (clave, valor)."""
try:
return dict(pairs)
except Exception as e: # ValueError por pares inválidos, etc.
raise ValueError("Se esperaban pares (clave, valor) válidos") from e
def get(d: Any, key: Any, default: Any = None) -> Any:
"""Obtiene d[key] o devuelve default si no existe."""
base = _ensure_dict(d)
return base.get(key, default)
def has_key(d: Any, key: Any) -> bool:
"""True si key está en d."""
base = _ensure_dict(d)
return key in base
def set_item(d: Any, key: Any, value: Any) -> Dict[Any, Any]:
"""Devuelve un nuevo dict con (key=value) sin mutar d."""
base = _ensure_dict(d)
nuevo = dict(base)
nuevo[key] = value
return nuevo
def remove(d: Any, key: Any) -> Tuple[Dict[Any, Any], Any]:
"""Elimina key de d y devuelve (nuevo_dict, valor). Lanza KeyError si no existe."""
base = _ensure_dict(d)
if key not in base:
raise KeyError(key)
nuevo = dict(base)
val = nuevo.pop(key)
return nuevo, val
def discard(d: Any, key: Any, default: Any = None) -> Tuple[Dict[Any, Any], Any]:
"""Elimina key si existe; si no, devuelve default. Nunca lanza error."""
base = _ensure_dict(d)
nuevo = dict(base)
if key in nuevo:
val = nuevo.pop(key)
return nuevo, val
return nuevo, default
def keys_list(d: Any) -> List[Any]:
"""Devuelve lista de claves (para comparar en tests usar set o sorted)."""
base = _ensure_dict(d)
return list(base.keys())
def values_list(d: Any) -> List[Any]:
base = _ensure_dict(d)
return list(base.values())
def items_list(d: Any) -> List[Tuple[Any, Any]]:
base = _ensure_dict(d)
return list(base.items())
def update(d: Any, updates: Dict[Any, Any]) -> Dict[Any, Any]:
"""Devuelve un nuevo dict con d actualizado por updates."""
base = _ensure_dict(d)
if not isinstance(updates, dict):
raise ValueError("updates debe ser un dict")
nuevo = dict(base)
nuevo.update(updates)
return nuevo