Dictionary and JSON: structured data
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
3JSON 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"}
foydalanuvchiIn 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.dumpsgoes from dictionary to text,json.loadsfrom text to dictionary.- Path into nested data:
d["a"][1]["b"].
Exercise
What does json.loads(matn) do?
Answer and explanation
- It turns JSON text into a Python dictionary (or list). (correct answer)
loadsreads the text and builds a Python data structure. - It writes the dictionary to a file.writing to a file is a different action;
loadsdoes not touch files. - It translates the text into another language.the
jsonmodule does not translate, it only changes the format.
Code exercises
- Create a dictionary
model: keynomwith the value “Mini”, keyversiyawith the value 2. Then print the value ofnom.
Hint: Dictionary:{"key": value, ...}. Reading a value:model["nom"]. - 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.
