AI Ustoz UZ: learn artificial intelligence in Uzbek

Dictionary and JSON: structured data

Beginner level · lesson 3 · about 12 min

A dictionary stores key and value pairs in curly braces. You get a value through its key: dictionary["key"]. Changing a value works the same way: dictionary["key"] = new.

model = {"nom": "Mini", "versiya": 2}
print(model["nom"])
model["versiya"] = 3
print(model["versiya"])
OutputMini
3

JSON is a format for exchanging data as text; it looks very much like a Python dictionary and list. Programs, including artificial intelligence services, often send each other JSON. Python’s json module: json.dumps(dictionary) turns a dictionary into text, json.loads(text) turns text into a dictionary.

import json

paket = {"rol": "foydalanuvchi", "matn": "Salom"}
matn = json.dumps(paket)
print(matn)
qayta = json.loads(matn)
print(qayta["rol"])
Output{"rol": "foydalanuvchi", "matn": "Salom"}
foydalanuvchi

In complex responses data sits in layers. You write the path to the value you need as a chain of keys and indexes, for example d["xabarlar"][1]["matn"]: first the “xabarlar” list, then its second item (index 1), then the “matn” value.

Remember

  • Dictionary: {"key": value}, reading: dictionary["key"].
  • json.dumps goes from dictionary to text, json.loads from text to dictionary.
  • Path into nested data: d["a"][1]["b"].

Exercise

What does json.loads(matn) do?

Answer and explanation
  1. It turns JSON text into a Python dictionary (or list). (correct answer)loads reads the text and builds a Python data structure.
  2. It writes the dictionary to a file.writing to a file is a different action; loads does not touch files.
  3. It translates the text into another language.the json module does not translate, it only changes the format.

Code exercises

  1. Create a dictionary model: key nom with the value “Mini”, key versiya with the value 2. Then print the value of nom.
    Hint: Dictionary: {"key": value, ...}. Reading a value: model["nom"].
  2. From the data in d, print the text of the user’s message (the second item).
    Hint: d["xabarlar"] is a list; the second item has index 1; then take its ["matn"] value.

Do the exercise in the app.

Practical task

Make a dictionary about yourself (name, age, city) and print it as text with json.dumps. You do not have to write real personal details.

  • I made a dictionary
  • I got text with json.dumps

Glossary

Interactive mode: search, progress and Python exercises.