Register to get access to free programming courses with interactive exercises

Syntax Python: Dictionaries and Sets

Like other built-in collections, Python supports it and has their syntax for describing literals. Programmers write dictionary literals in curly brackets, separate key-value pairs by commas, and separate the key from the value by colons:

dictionary = {
    "foo": "bar",
    "baz": 42,
    "items": {
        1: "apple",
        2: "orange",
        100500: "lemon"
dictionary  # {'foo': 'bar', 'baz': 42, 'items': {1: 'apple', 2: 'orange', 100500: 'lemon'}}

In this example, there are both string and number keys, and one of the values is a nested dictionary. And variables, of course, can act as values and keys:

key, val = 'x', 42
{key: val}  # {'x': 42}

Accessing items by keys

Above, we declared a dictionary called dictionary. You can request a key value from it like this:

dictionary["baz"]  # 42
dictionary["BANG"]  # KeyError: 'BANG'

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.