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'

There is no "BANG" key in the dictionary, so we get a KeyError exception, which is the equivalent of IndexError for dictionaries. You can check the presence of a key in the dictionary using the in operator, which you already know:

"baz" in dictionary  # True
"BANG" in dictionary  # False

Now, if you want to get a value by a key that may not exist, you can do it like this:

dictionary["BANG"] if "BANG" in dictionary else None

However, such a secure element request is needed so often that the dictionary object has a specific .get method for this:

dictionary.get("baz")  # 42
dictionary.get("BANG")  # It returns `None`
dictionary.get("BANG", "no such key")  # 'no such key'

The third method call shows how we can set the default value explicitly. When we do not specify it, the method will return None if there is no value for the specified key.

Using the keys, values, and items iterators

If we try to iterate through the dictionary, we'll get a list of keys:

for k in {"a": 1, "b": 2}:
    print(k)

# => a
# => b

We can achieve the same result more explicitly, which you'll need to call the .keys() method for:

list({"a": 1, "b": 2}.keys())  # ['a', 'b']

To get the values, you need to call the .values() method:

list({"a": 1, "b": 2}.values())  # [1, 2]

And to get both the keys and the corresponding values at the same time, you can call the .items() method:

for k, v in {"a": 1, "b": 2}.items():
    print(k, "=", v)

# => a = 1
# => b = 2

Remember that dictionaries are unordered. Therefore, it is not worth building the logic of the code considering the order of the keys in the dictionary.


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

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: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
new
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.