Introduction to Python dictionaries

A quick and dirty introduction to dictionaries in Python.

Dictionaries are a special container type. Each element has a key. This allows targeted search and data retrieval. However, dictionaries also have disadvantages vs. e.g. lists. E.g. a list is used when entries should be sorted easily.

a dictionary is declared using {} brackets; in between { and } dictionaries kontakt “key”:value pairs

dict1 = {"key1" : 1,
        "key2" :2}

values can be retrieved by using the key

dict1["key2"]
2

dictionaries can also be declared usign the dict() function / constructor

dict2 = dict()
print(dict2)
{}
dict2
{}

values in a dictionary can be changed

dict3 = {
    "a":1,
    "b":2,
    "c":3}
dict3["b"] = "text"
print(dict3)
{'a': 1, 'b': 'text', 'c': 3}

accessing values by entering the key between square brackets is only one way; another one is using get()

dict3.get("b")
'text'

it is possible to loop through dictionaries

# the dictionary as such
for i in dict3:
    print(i)
a
b
c
# this is the same as iterating through the .keys()
for i in dict3.keys():
    print(i)
a
b
c
# but, I can also iterate through the .values()
for i in dict3.values():
    print(i)
1
text
3
# looping through BOTH KEYS and VALUES is also not a problem, using .items()
for i, j in dict3.items():
    print (i,j)
a 1
b text
c 3

dictionaries allow for some logic tests; e.g. whether a certain key is contained by the dictionary

"b" in dict3
True
"d" in dict3
False

furthermore, it is also possible to determine the length of a dictionary – using len()

len(dict3)
3
len(dict1)
2

items can be added to a dictionary, as demonstrated below:

dict3["d"] = 4
print(dict3)
{'a': 1, 'b': 'text', 'c': 3, 'd': 4}

items can be popped, using pop() (for defined key) or popitem() for most recently added item

dict3.pop("d")
4
dict3.popitem()
('c', 3)
# as seen with python lists pop() and popitem() return and remove elements / items
print(dict3)
{'a': 1, 'b': 'text'}

items or entire dictionaries can be deleted from a dictionary, using the del command

del dict3["b"]
print(dict3)
{'a': 1}
del dict3
print(dict3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-b91794b7e8de> in <module>
      1 del dict3
----> 2 print(dict3)

NameError: name 'dict3' is not defined

clear() clears the entire dictionary, making it empty

dict4 = {"1":1,
         "2":2,
         "3":3,
         "4":4}
print(dict4)
{'1': 1, '2': 2, '3': 3, '4': 4}
dict4.clear()
print(dict4)
{}

shallow copies of python dictionaries can be made using .copy() method

dict5 ={"a":200,"b":300,"c":500}
dict6 = dict5.copy()
print(dict5)
print(dict6)
{'a': 200, 'b': 300, 'c': 500}
{'a': 200, 'b': 300, 'c': 500}
dict6.clear()
print(dict5)
print(dict6)
{'a': 200, 'b': 300, 'c': 500}
{}

the same can be achieved using the dict() function, which is NOT a dictionary method

dict7 = dict(dict5)
print(dict5)
print(dict7)
{'a': 200, 'b': 300, 'c': 500}
{'a': 200, 'b': 300, 'c': 500}
dict7["b"] = 100000
print(dict5)
print(dict7)
{'a': 200, 'b': 300, 'c': 500}
{'a': 200, 'b': 100000, 'c': 500}

it is possible to nest dictionaries inside eachother:

# two-dimensional python dictionary
dict8 = {
    "dict_01" : {
        "key1":"a",
        "key2":"b"
    },
    "dict_02" : {
        "key1":"c",
        "key2":"d"
    }
}
print(dict8)
{'dict_01': {'key1': 'a', 'key2': 'b'}, 'dict_02': {'key1': 'c', 'key2': 'd'}}
# accessing a first level item (e.g. the first sub-dictionary)
dict8["dict_01"]["key2"]
'b'

You May Also Like

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.