Python Dictionary

Dictionary is an unordered, changeable and indexed collection of items. Dictionary doesn’t have duplicate items.  Dictionary consist of key and value pair. Keys are unique, where as values can be and can not be unique. Values can be any item such as integer, string, dictionary, set, tuple etc. 

Creating a dictionary

Dictionary is creating using curly brackets ( { }  ). Let’s look at some of the example of dictionary.

Example:

# an empty dictionary
empty_dict = {}

# dictionary with value
my_dict = {
    'one': 1,
    'two': 2
}

Selecting an item from a dictionary

We can select item from a dictionary using indexing with key item.

For example

my_dict = {
    'one': 1,
    'two': 2
}

print(my_dict['one'])
print(my_dict['two'])

Output:

1
2

We can also use  get(keyitem)  method to get the value of a dictionary. For example

my_dict = {
    'one': 1,
    'two': 2
}

print(my_dict.get('one'))
print(my_dict.get('two'))

Output:

1
2

Updating item in a dictionary

You can change the dictionary value by referring to it’s key name.

Example

my_dict = {'one': 1, 'two': 2}
print(my_dict)

# updating values using existing key
my_dict['one'] = 1.5
my_dict['two'] = 2.5
print(my_dict)

Output:

{'one': 1, 'two': 2}
{'one': 1.5, 'two': 2.5}

Adding item to a existing dictionary

Adding item is similar to updating, while adding we give new index key and assign it to a value.

Example:

 my_dict = {'one': 1, 'two': 2}
print(my_dict)

# updating values
my_dict['three'] = 3
my_dict['four'] = 4
print(my_dict)

Output:

{'one': 1, 'two': 2}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}

Deleting item from a dictionary

Deleting item can be achieved in 3 ways

  • using  del   keyword
  • using  .pop(key)  method
  • using  .popitem()  method 

del    and .pop(key) method uses key to delete the dictionary.  del   keyword can also delete entire dictionary. The .popitem() method removes the last item from the dictionary.

Example:

my_player_dict = {
    'player1': 1,
    'player2': 2,
    'player3': 3,
    'player4': 4,
    'player5': 5
}
print("original=", my_player_dict)

# removing item using del
del my_player_dict['player1']
print(my_player_dict)

# removing item using .pop()
my_player_dict.pop('player2')
print(my_player_dict)

# removing item using popitem()
my_player_dict.popitem()
print(my_player_dict)

Output:

original= {'player1': 1, 'player2': 2, 'player3': 3, 'player4': 4, 'player5': 5}
{'player2': 2, 'player3': 3, 'player4': 4, 'player5': 5}
{'player3': 3, 'player4': 4, 'player5': 5}
{'player3': 3, 'player4': 4}

Deleting an entire dictionary

You can use del keyword to delete an entire dictionary.

my_dict = {'one': 1, 'two': 2}
del my_dict
print(my_dict)

This print statement will throw error saying ‘my_dict’ is not defined. This is because we have deleted it using del keyword. You will have similar output as below.

Output:

Traceback (most recent call last):
  File "/home/PythonCourseCreation/python_code/15_dictionary.py", line 67, in <module>
    print(my_dict)
NameError: name 'my_dict' is not defined

Looping through an item in dictionary

Looping through items in the dictionary is simple. We can get both key and value using the .items()  method in a dictionary. The .items() method returns a tuple with key and value pair, therefor we have to grab both of them.  Let’s see an example.

Example:

my_dict = {'one': 1, 'two': 2}
for key, item in my_dict.items():
    print(key, item)

Output:

one 1
two 2

If you want to get only key then simply loot through dictionary without any method will give you keys in the dictionary. If you want to get only values we can use .values()     method to get only values. 

Let’s see an example:

my_dict = {'one': 1, 'two': 2}
for key in my_dict:
    print(key)

print("With only values")
my_dict = {'one': 1, 'two': 2}
for value in my_dict.values():
    print(value)

Output:

one
two
With only values
1
2

Copying a dictionary

When we assign a dictionary to another dictionary using equal to operator we make a reference to an original dictionary. Whenever one dictionary changes the other also changes. Let’s see an example:

original_dict = {'one': 1, 'two': 2}
second_dict = original_dict
print(original_dict)
print(second_dict)

# adding item to second
second_dict['three'] = 3
# original dict also changes
print('original=', original_dict)
print('second=', second_dict)

# adding item to original
original_dict['four'] = 4

print('original = ', original_dict)
print('second = ', second_dict)

Output:

{'one': 1, 'two': 2}
{'one': 1, 'two': 2}
original= {'one': 1, 'two': 2, 'three': 3}
second= {'one': 1, 'two': 2, 'three': 3}
original =  {'one': 1, 'two': 2, 'three': 3, 'four': 4}
second =  {'one': 1, 'two': 2, 'three': 3, 'four': 4}

As you can see using equal to operator make a reference link to original situation. But if you need to actually copy content from a dictionary and make sure that changing one does not change another then you can use .copy()  method in a dictionary. 

Let’s see an example.

Example:

original_dict = {'one': 1, 'two': 2}
second_dict = original_dict.copy()
print(original_dict)
print(second_dict)

# adding item to second
second_dict['three'] = 3
# original dict also changes
print('original=', original_dict)
print('second=', second_dict)

# adding item to original
original_dict['four'] = 4
print('original = ', original_dict)
print('second = ', second_dict)

Output:

{'one': 1, 'two': 2}
{'one': 1, 'two': 2}
original= {'one': 1, 'two': 2}
second= {'one': 1, 'two': 2, 'three': 3}
original =  {'one': 1, 'two': 2, 'four': 4}
second =  {'one': 1, 'two': 2, 'three': 3}

Length of a dictionary

Length of a dictionary can be determined using len(iterable_item)  method.

Example,

my_dict = {'one': 1, 'two': 2}
print(len(my_dict))

Output:

2

Leave a Reply

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