DEV Community


Posted on

Bite-Size Python: Dictionaries basic

As the name imply, dictionary consists of keys and values mapping so that we can lookup for the value using the key the same way we lookup for the meaning of the word.

This post will show some basic operation on dictionaries like dictionary creation, modification and so on.

Let's start!

Dictionary creation

# create empty list
>>> a_dict = {}
# or
>>> a_dict = dict()

# create with some value
# key's in the dictionary can be mix with some other types
>>> a_dict = {"key1": "value1", 2: "two", "three": 3} 
>>> a_dict
{'key1': 'value1', 2: 'two', 'three': 3}

# or using dict() with sequence of key-value pairs
# like list of a pair of tuple
>>> a_dict = dict([("key1", "value1"), (2, "two"), ("three", 3)])
>>> a_dict
{'key1': 'value1', 2: 'two', 'three': 3}

Accessing dictionary value

# using the same manner of accessing list element 
# but use the key instead of index number
>>> a_dict["key1"]
# or using get()
>>> a_dict.get(2)
# the main difference between these two is 
# get() will return None if the key is not found 
# in the dictionary but the other will raise the KeyError exception
# so, your program will break if the error's raise, so be careful
>>> a_dict.get("python")
>>> # noting happen

>>> a_dict["python"]
KeyError: 'python'

# you can check whether the key is available 
# in the dictionary or not using `in` syntax
>>> "key1" in a_dict
>>> "python" in a_dict

Dictionary modification

# modify the existing value
>>> a_dict["key1"] = "one"
>>> a_dict
{'key1': 'one', 2: 'two', 'three': 3}

# adding new key-value pair
>>> a_dict["python"] = "snake"
>>> a_dict
{'key1': 'one', 2: 'two', 'three': 3, 'python': 'snake'}

# delete using `del`
>>> del a_dict[2]
>>> a_dict
{'key1': 'one', 'three': 3, 'python': 'snake'}

Iterating over dictionary

# we can iterate over dictionary using looping statement like `for-loop` with items() to get both key and value pair for each member
>>> for k, v in a_dict.items():
key1 : one
three : 3
python : snake

# getting keys only using keys()
>>> a_dict.keys() 
dict_keys(['key1', 2, 'three'])

# as you expect, we can get only values too!
>>> a_dict.values()
dict_values(['one', 3, 'snake'])

I hope this can help you to getting start using dictionary in Python.

Thanks for reading! :)

Top comments (0)