Guide to Python Dictionary data with its methods

In our previous articles, we learn different data types available in Python. Python Dictionary is one of the data types in Python, Dictionary is like a list, where values are stored in key and value pair.

In this tutorial, we’ll have three objectives. First learn the Python dictionary in detail with an example, Second what are different methods available on the Dictionary objects, and third when to use dictionary data.

Python Dictionary in details
Python Dictionary keys and value

What is Python Dictionary?

A data dictionary is similar to a list, except that each item in the list has a unique key. Dictionary is an object that store a collection of data in name-value pairs. Whose values are accessible by key, and the value we associate with a key can be a number, string, tuple, or list.

Characteristics of Python Dictionary

Dictionary is a mutable object and index by key, here values are stored in key and value pairs and we can’t index on the dictionary as we do in a string, list, and tuple. Dictionary data types have the following features

  1. It stores data in key-value pairs. The key of dictionary collection is always unique, we can’t use the same key more than once.
  2. We can easily retrieve values using keys from dictionary collection. The time complexity of retrieving value using a key is the same even though we have billion of records in a dictionary.
  3. Dictionary mutable objects are changeable we can add or remove items in a dictionary. But Keys must be immutable objects: ints, strings, tuples, etc

Dictionaries are unordered collections and we can define them by {} curly brace like object in Javascript. Syntax of Dictionary data type.

const someDictionary = { key1: someValue1, key2: someValue2 ...... keyn: someValuen }

Before going deep into Dictionary, let’s demonstrate a small introduction example on the dictionary I hope looking at this example, you will get some idea about Dictionary in general.

Python Dictionary operation in general
Python Dictionary Methods

How to create and initialize Python Dictionary?

Now we have got some idea on Dictionary. Let’s create a simple example to demonstrate it. For the below example we have a student marks dictionary. Where English, math, and physic are keys of the dictionary and numbers are their corresponding value.

#Create dictionary using with subject name as key and mark obtain as value
marks = { 'english': 60, 'math': 90, 'physic': 90 };

#Print all values from marks dictionary
print(marks.values());
#Output  :    dict_values([60, 90, 90])

#Print all keys from marks dictionary
print(marks.keys());
#Output : dict_keys(['english', 'math', 'physic'])

In Python, we can initialize the dictionary in two different ways as follow.

  1. Using curly brackets, Each entry consists of a pair separated by a colon. The first part of the pair is called the key and the second is the value.
  2. We can use a built-in function or constructor called dict. This function takes a number of key-value pairs as arguments and returns the corresponding dictionary.

Create Python Dictionary data using {} curly brace

An element consists of a key, followed by a colon, followed by a value. In the first Python dictionary example, let’s create a dictionary of weekDay using curly brace {}, where the Wilday name is key and the number is value.

#Dictionary declaration using { }
weekDay = { 
     'monday': 1,
     'tuesday': 2,
     'wednesday': 3,
    'thursday': 4,
    'friday': 5,
    'saturday': 6,
    'sunday': 7
};

Create a Python dictionary using dict constructor or function

We can use dict constructor function to create a dictionary and we need to pass a list of keys and values as an argument to dict function.

#Dictionary declaration using dict function
weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7)
Note: It’s important that the default value for the dictionary is none rather than an empty dictionary, for example ({}). dict_emp={} Output {}

How to access Element in Python Dictionary keys?

The simplest way to retrieve a value from a dictionary is using a key with a square bracket, we simply write an expression in the following
general format:

dictionary_name[key]

Accessing element using Python dictionary key with a square bracket

Where dictionary_name is the variable that references the dictionary, and the key is a key. Using index for­­ access element or add items to a dictionary with the indexing operator [ ]. Example:

hotels = {'Taj hotel': 'Tata', 'Oberoi hotel': 'The Oberoi Group', 'The Leela Palaces': 'Brookfield Asset Management' };

key = 'Taj hotel';
if key in hotels: print(hotels[key]);     #Outp Tata

Example two of using a key to add a new element to the dictionary.

actors = {}
actors['name'] = 'Keane'
actors[age'] = 50
print actors
Out: {'age': 50, 'name': 'Keane'}

Using the Looping technique to access the Python Dictionary element

We can access using a different approach, A dictionary itself is iterable: it iterates over its keys. So let’s iterate the dictionary using for loop.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);
for k in weekDay: print(k);

#Output
monday
tuesday
wednesday
Thursday
Friday
Saturday
Sunday

We can use the items() method of the dictionary to retrieve the key and its corresponding value. Here is an example of it.


weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);

for key, value in weekDay.items(): print(key, value)

#Output
monday 1
tuesday 2
wednesday 3
Thursday 4
Friday 5
Saturday 6
Sunday 7

Python dictionary methods

In our previous articles, we learn that everything in Python is an object and even variables are objects of having a type. The dictionary datatype too is an object, the dictionary has a lot of methods that are handy and we can use it to perform an operation on a dictionary. Here I had listed some of the methods of it.

S.noFunction nameDescription
1keys() The keys method returns all keys in a dictionary.
2values()The values method returns all values in a dictionary
3items()The items method returns all key-value pairs in a dictionary.
4get(‘key’)The get value associated with the key if the key exists or none if a key does not exist.
5setdefault(‘newKey’, 10)Add a new record to a dictionary if the key does not exist and is so then don’t change the existing key and value.
6clear()Clear Clears the contents of a dictionary.
7pop(key)Returns the value associated with a specified key and removes that key-value
pair from the dictionary. If the key is not found, the method returns a default
value.
8popitem()The method removes the key-value pair of elements that was last added to the dictionary
9append()The append method is to add a new record or edit the existing key value.
Python dictionary methods

The keys method returns all keys in a dictionary, the values method returns all values in a dictionary, and the items method returns all key-value pairs in a dictionary.

print(weekDay.keys());

#Output of keys 
dict_keys(['monday', 'tuesday', 'wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])

Let’s demonstrate a few examples of this method.

1. Dictionary keys() method

As we know that a dictionary is an object and its skeys() returns all the keys in the dictionary. Here is an example of it.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);
print(weekDay.keys());

#Output
dict_keys(['monday', 'tuesday', 'wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])

2. Dictionary values() method

The Dictionary get method, return all values in a dictionary and let use the above weekDay example.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);

print(weekDay.values());

#Output
dict_values([1, 2, 3, 4, 5, 6, 7])

3. Dictionary gets() method

Dictionary gets() method to return all keys and their corresponding value in a dictionary object.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);

print(weekDay.items())

#Output
dict_items([('monday', 1), ('tuesday', 2), ('wednesday', 3), ('Thursday', 4), ('Friday', 5), ('Saturday', 6), ('Sunday', 7)])

4. Removing a key value in Python Dictionary using a pop method

In Dictionary we can remove or delete a key value using a pop() method, here we need to specifically give the key as a parameter in the pop() method. In this example, we want to remove Saturday using the Saturday key in the pop() method.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);
weekDay.pop('Saturday');
print(weekDay.items())

#Output
dict_items([('monday', 1), ('tuesday', 2), ('wednesday', 3), ('Thursday', 4), ('Friday', 5), ('Sunday', 7)])

5. Removing a key value in Dictionary using a pop method

Dictionary also has the popItem() method without any argument to remove or delete the last element in Dictionary.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);
weekDay.popitem();
print(weekDay.items())

#Output
dict_items([('monday', 1), ('tuesday', 2), ('wednesday', 3), ('Thursday', 4), ('Friday', 5), ('Saturday', 6)]);

6. Dictionary clear() method

If we want to clear the content of the dictionary, we can use the clear() method from the Dictionary object. The clear method deletes all the elements in a dictionary, leaving the dictionary empty.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);
weekDay.clear();

print(weekDay.items());
#Output
ict_items([])

Python Dictionary delete key

In previous example we have use clear(), pop() and popItem() to remove element in Dictionary. We can use the delete key to remove elements in a dictionary and we need to pass the key of the record which we want to remove in the Dictionary.

weekDay = dict( monday = 1, tuesday = 2, wednesday =3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7);
del weekDay['Saturday'];

print(weekDay.items());

#Output
dict_items([('monday', 1), ('tuesday', 2), ('wednesday', 3), ('Thursday', 4), ('Friday', 5), ('Sunday', 7)])

Using the in and not in Operators to Test for a Value in a Dictionary

Like del keyword, we can use in and not in operators to test if a key exists in the dictionary. Let’s demonstrate this keyword to check if the key exists in a Dictionary.

weekDay = dict( Monday = 1, Tuesday = 2,Friday = 5, Saturday = 6, Sunday = 7, Wednesday =3, Thursday = 4);

if 'July' in weekDay: 
 print(weekDay['July']);
else: 
 print('July not exist');

#Output
July not exist


if 'Friday' in weekDay: 
 print(weekDay['Friday']);
else: 
 print('Firday not exist');
 
#Output 5

The not in keyword is the opposite of the in, here we check if the key is not inside a Dictionary. Here is an example of it.

if 'Friday' not in weekDay: 
 print('Friday not exist');
else: 
 print(weekDay['Friday']);

#Output 5

Adding Elements to an Existing Python Dictionary

We know that Python Dictionary objects are mutable and we can add or remove any element during our program execution. We can use dictionary names with a square bracket and a new key to add elements to an existing Dictionary. Here is a syntax for adding new elements to the existing dictionary.

dictionary_name[key] = value
If a key already exists in the dictionary, its associated value will be changed to value. If the key does not exist, it will be added to the dictionary, along with value as its associated value.
hotels = {'Taj hotel': 'Tata', 'Oberoi hotel': 'The Oberoi Group', 'The Leela Palaces': 'Brookfield Asset Management' };

#Add new hotel
hotels['Hotel Trump Plaza'] = 'The Trump Organization';
print(hotels);

#Output
{'Taj hotel': 'Tata', 'Oberoi hotel': 'The Oberoi Group', 'The Leela Palaces': 'Brookfield Asset Management', 'Hotel Trump Plaza': 'The Trump Organization'}

Python List of Dictionaries

In the Python dictionaries list, keys in a dictionary must be immutable objects and their corresponding value can be any type. In our above almost all example we use Python List of Dictionaries where is value is either number or string, now let add Python list of Dictionaries value with array object instead of a regular string or number.

result = { 
   'Reaves' : [90, 50, 70, 90], 
   'Smith' : [30, 40, 20, 50],
   'Vijay' : [92, 90, 100, 100],
   'George' : [20, 45, 66,87] 
}

print(result);

#Output
{'Reaves': [90, 50, 70, 90], 'Smith': [30, 40, 20, 50], 'Vijay': [92, 90, 100, 100], 'George': [20, 45, 66, 87]}

Python Dictionary append

We can use Python Dictionary append method to add a new record if the key does not exist or update the existing value of the key which we pass as an argument in the append method.

result = { 
   'Reaves' : [90, 50, 70, 90], 
   'Smith' : [30, 40, 20, 50],
   'Vijay' : [92, 90, 100, 100],
   'George' : [20, 45, 66,87] 
}

#Python Dictionary append to update exist record of Reaves
result['Reaves']=[100, 100, 100, 100];
print(result);

#Output
{'Reaves': [100, 100, 100, 100], 'Smith': [30, 40, 20, 50], 'Vijay': [92, 90, 100, 100], 'George': [20, 45, 66, 87]}

#Append new record to existing Dictionary
result['Edupala']=[50, 50, 50, 50];

#Output
{'Reaves': [90, 50, 70, 90], 'Smith': [30, 40, 20, 50], 'Vijay': [92, 90, 100, 100], 'George': [20, 45, 66, 87], 'Edupala': [50, 50, 50, 50]}

Note: If you don’t have Python installed in your system, you can use an online python IDE or editor likes. https://www.online-python.com/

Conclusion
In Dictionary is a collection of data in key and values pairs, we can easily and very fast access any value in the dictionary using its corresponding key. But in List data collection we access elements using index this is different. We have tried to cover most of the Dictionary and I hope you learn something. Happy coding and if this article is useful then please share it with others or on social networking. Thanks

Related Articles on Python

  1. Python String and Methods tutorial
  2. Python variable and its types in details
  3. Python function and its types

Leave a Comment

Your email address will not be published.

Scroll to Top