3.8.1. Creating dictionaries and accessing/modifying entries#
A dictionary is created using curly braces {}
and colons :
, using a “key: value” syntax:
empty_dict = {}
dict_of_integers = {1: 11, 2: 22, 5: 55}
Here, we used integers for both the keys and values, but in reality:
the key can be of many types such as integers or strings;
the value can be of any type.
dict_of_anything = {
1: "String for integer key 1",
2: "String for integer key 2",
"three": "String for string key 'three'",
"some_int_value": 10,
"some_float_value": 10.0,
"some_list": [1, 3, 5, 7],
"some_nested_dict": {
"a": "A",
"b": "B",
},
}
To access a dictionary entry, we use []
, exactly as we would index a list or tuple:
dict_of_anything[2]
'String for integer key 2'
dict_of_anything["three"]
"String for string key 'three'"
dict_of_anything["some_nested_dict"]
{'a': 'A', 'b': 'B'}
To change the value of an existing element:
dict_of_anything[2] = 66
dict_of_anything
{1: 'String for integer key 1',
2: 66,
'three': "String for string key 'three'",
'some_int_value': 10,
'some_float_value': 10.0,
'some_list': [1, 3, 5, 7],
'some_nested_dict': {'a': 'A', 'b': 'B'}}
We can list the available keys in a dictionary using its keys
method:
dict_of_anything.keys()
dict_keys([1, 2, 'three', 'some_int_value', 'some_float_value', 'some_list', 'some_nested_dict'])
or we can test if the dict contains a certain key using the in
keyword:
print(1 in dict_of_anything)
print(3 in dict_of_anything)
True
False