Python Dictionary Python

Jul 30th, 2021 - written by Kimserey with .

Python dictionary is a structure that can be used to store key/value data with constant time for access. Dictionary structures in Python are very versatile which makes them popular and we can see them being used in many projects. They allow us to store keys and values of different types, provide us ways to iterate over the keys or values and have different ways to delete values. In today’s post, we will explore all the functionalities of dictionaries in Python.

Create Dictionary

To create a dictionary, we can use the braces syntax:

1
2
3
4
a = { 'hello': 1, 'world': 2 }

a
{'hello': 1, 'world': 2}

Or we can create a dictionary out of a set of values:

1
2
3
4
b = dict.fromkeys(['hello', 'world'])

b
{'hello': None, 'world': None}

Add Value

Adding value to dictionaries can be done via index:

1
a["test"] = "something"

We can also use setdefault to set the value if it doesn’t exist yet:

1
a.setdefault("test", "xyz")

But this can easily be achieve with in:

1
2
if test not in a:
    a["test"] = "xyz

Access Values

To access data, we can do so by the index:

1
a["test"]

But this will throw an exception if the key doesn’t exist:

1
2
3
4
5
6
7
a["hehe"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-a43b1e5d2f11> in <module>
----> 1 a["hehe"]

KeyError: 'hehe'

In order to get a value without exception being thrown we can use get:

1
a.get("hehe")

This will return None if the key doesn’t exists, or we can specify a default value to return:

1
2
a.get("hehe", -1)
-1

Delete Values

Deleting values from a dictionary can be done with del:

1
del a["test]

Or we can also pop a value given a key, which will delete the key/value pair while returning the value:

1
a.pop("test")

Or we can also use popitem, which pops the last key/value pair from the dict and returns it:

1
2
a.popitem()
("test", 10)

Iterate over values

Lastly we can also use dictionaries to keep unique keys and associated values and iterate over all of them.

We can iterate over each key/value as a list by using items:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
In [1]: a["test"] = 10

In [2]: a["hello"] = 20

In [3]: a
Out[3]: {'test': 10, 'hello': 20}

In [4]: a.items()
Out[4]: dict_items([('test', 10), ('hello', 20)])

In [5]: for k, v in a.items():
    ...:     print(k, v)
    ...: 
test 10
hello 20

Or we can just iterate over the values with values:

1
2
3
4
5
6
In [6]: for v in a.values():
    ...:     print(v)
    ...: 
    ...: 
10
20

Or just the keys:

1
2
3
4
5
6
7
In [7]: for k in a.keys():
    ...:     print(k)
    ...: 
    ...: 
    ...: 
test
hello

Conclusion

In today’s post, we looked at Python dictionary. We saw the way we could save values, access them, delete them and lastly iterate over all of them. I hope you liked this post and I see you on the next one!

Designed, built and maintained by Kimserey Lam.