🐍

Introducere in Dictionare

Programare Python Intermediar 1 min citire 0 cuvinte

Introducere in Dictionare

Ce este un Dictionar?

Un dictionar este o colectie neordonata de perechi cheie-valoare. Fiecare cheie este unica si mapeaza la o valoare.

Crearea Dictionarelor

# Cu acolade
student = {"nume": "Ana", "varsta": 20, "nota": 9.5}

# Dictionar gol
gol = {}
gol2 = dict()

# Cu dict()
student2 = dict(nume="Bob", varsta=22)

# Din lista de tupluri
perechi = [("a", 1), ("b", 2)]
d = dict(perechi)  # {'a': 1, 'b': 2}

# Dict comprehension
patrate = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Accesarea Valorilor

Cu cheie directa [key]:

student = {"nume": "Ana", "varsta": 20}

print(student["nume"])    # Ana
print(student["varsta"])  # 20

# KeyError pentru cheie inexistenta
# print(student["nota"])  # KeyError!

Cu metoda get():

student = {"nume": "Ana", "varsta": 20}

print(student.get("nume"))        # Ana
print(student.get("nota"))        # None (nu arunca eroare)
print(student.get("nota", 0))     # 0 (valoare default)
print(student.get("varsta", 0))   # 20 (cheia exista)

Modificarea si Adaugarea

student = {"nume": "Ana", "varsta": 20}

# Modificare
student["varsta"] = 21
print(student)  # {'nume': 'Ana', 'varsta': 21}

# Adaugare (cheie noua)
student["nota"] = 9.5
print(student)  # {'nume': 'Ana', 'varsta': 21, 'nota': 9.5}

Verificarea Cheilor

Operatorul in verifica cheile, nu valorile:

student = {"nume": "Ana", "varsta": 20}

print("nume" in student)     # True
print("nota" in student)     # False
print("Ana" in student)      # False (Ana e valoare!)

print("nota" not in student) # True

Cheile Dictionarului

Cheile trebuie sa fie hashable (imutabile):

# Chei valide
d = {
    "string": 1,
    42: "numar",
    (1, 2): "tuplu",
    True: "bool"
}

# Chei INVALIDE
# d = {[1, 2]: "lista"}  # TypeError - lista nu e hashable
# d = {{}: "dict"}       # TypeError - dict nu e hashable

Valori in Dictionar

Valorile pot fi de orice tip:

complex_dict = {
    "nume": "Ana",
    "note": [9, 10, 8],
    "adresa": {"oras": "Cluj", "strada": "Unirii"},
    "activ": True
}

print(complex_dict["note"][0])           # 9
print(complex_dict["adresa"]["oras"])    # Cluj

Stergerea Elementelor

student = {"nume": "Ana", "varsta": 20, "nota": 9}

# del
del student["nota"]
print(student)  # {'nume': 'Ana', 'varsta': 20}

# pop() - sterge si returneaza
varsta = student.pop("varsta")
print(varsta)   # 20
print(student)  # {'nume': 'Ana'}

# pop() cu default
nota = student.pop("nota", None)
print(nota)  # None (nu arunca eroare)

Iterarea prin Dictionare

student = {"nume": "Ana", "varsta": 20, "nota": 9}

# Doar cheile (implicit)
for cheie in student:
    print(cheie)
# nume, varsta, nota

# Explicit cheile
for cheie in student.keys():
    print(cheie)

# Doar valorile
for valoare in student.values():
    print(valoare)
# Ana, 20, 9

# Chei si valori
for cheie, valoare in student.items():
    print(f"{cheie}: {valoare}")
# nume: Ana
# varsta: 20
# nota: 9

Lungime si Verificare

student = {"nume": "Ana", "varsta": 20}

print(len(student))  # 2

# Verificare dictionar gol
if student:
    print("Are elemente")
if not {}:
    print("Dictionar gol")

Dictionare Nested

studenti = {
    "s001": {"nume": "Ana", "nota": 9},
    "s002": {"nume": "Bob", "nota": 8}
}

print(studenti["s001"]["nume"])  # Ana
studenti["s001"]["nota"] = 10
print(studenti["s001"]["nota"])  # 10

# Adaugare student nou
studenti["s003"] = {"nume": "Cris", "nota": 7}

Greseli Frecvente

1. KeyError la acces direct

d = {"a": 1}
# d["b"]  # KeyError!
d.get("b")  # None - sigur

2. Confuzie in verifica cheile

d = {"a": 1}
print("a" in d)  # True - cheie
print(1 in d)    # False - 1 e valoare, nu cheie

3. Modificare in timpul iterarii

d = {"a": 1, "b": 2}
# GRESIT
# for k in d:
#     del d[k]  # RuntimeError!

# CORECT
for k in list(d.keys()):
    del d[k]

Puncte Cheie pentru Examen

  • Dictionare: perechi cheie-valoare
  • Cheile trebuie sa fie hashable (imutabile)
  • [] arunca KeyError, .get() returneaza None
  • in verifica cheile, nu valorile
  • Iterare: keys(), values(), items()
  • Valorile pot fi de orice tip

Intrebari de Verificare

  1. Ce returneaza {"a": 1}.get("b")?
  2. Ce tip de obiecte pot fi chei?
  3. Cum verifici daca o cheie exista in dictionar?
  4. Ce returneaza 1 in {"a": 1}?

📚 Articole Corelate