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'