Thursday, April 24, 2025

Dictionaries

 Dictionary: A data type built into Python


The dictionary is a compound data type in Python. Its basic items (elements) are key-value pairs. The key must be of an immutable data type (string, tuple, or number), and the value may be of any type, including lists and dictionaries.  Some examples are as values

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}

In this example, Python, Java and C++ are keys, and their corresponding values are 'data science', 'enterprise level', and 'system level.

The values in a dictionary are accessed using keys. Some examples with outputs (commented text) are as follows.

print(dict1['Python'])            # prints data science
print(dict1['Java'])                # prints enterprise level
print(dict1['C++'])                # prints system level

Keys in the dictionary are unique and adding a new item with the same key eliminates the earlier value. For example, updating the dict1 with an existing key but a different value yields the following result.

dict1['Python'] = 'scientific'
print(dict1)                   # prints {'Python': 'scientific', 'Java': 'enterprise level', 'C++': 'system level'}

This also shows that dictionaries are a mutable type. New items are added to the existing dictionary as follows.

dict1['C'] = 'system level'
print(dict1)    #{'Python': 'scientific', 'Java': 'enterprise level', 'C++': 'system level', 'C': 'system level'}

This also shows that added items appear at the end of the dictionary and different keys can have the same value. Searching for a non-existent key results in an error.

print(dict1['R'])           # Python interpreter throws KeyError 

An empty dictionary can be created using empty braces as follows.

dict2 = {}

The key-value pairs can be added dynamically to the existing dictionary.

in and not in operators with dictionary

The in and not in operators are useful to find whether a particular key exists in the dictionary or not. The following code snippet shows the usage of these to operators. 

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}
if 'Python' in dict1:
    print("Key  'Python' exists in dict1")            # True
else:
    print("Key  'Python' does not exist in dict1")
    
Similarly,
'R' not in dict1        # results in True
'R' in dict1        # results in False
It results in True and False.

Alternate ways of creating  dictionaries

The dict() constructors (based on oop concept) are used to create the dictionary as follows.

dict_new =  dict([('Python', 'data science'), ('Java', 'enterprise level'), ('C++', 'system level')])

By carefully observing, you can see that dict is similar to a function, and the argument is a list of tuples. If the keys are simple strings, the following simple way can be used to create new dicitonary.

dict_new =  dict(Python = 'data science', Java =  'enterprise level', C  =  'system level')

Observe that keys are without quotes, whereas values are within quotes. The ++ with C and = gives a syntax error and hence changed to 'C'.

Nested dictionary

It is possible to have a dictionary as a value for a key. The following code snippet shows the same and also accessing the nested dictionary values using keys.

nest_dict = {
    "student1": {"name": "Steve", "age": 19},
    "student2": {"name": "Peter", "age": 20}
}
stu_detail = nest_dict['student1']          # access the entire record of the student1 (inner dictionary)
print(stu_detail)
age_student1 = nest_dict["student1"]["age"]        # access the age of the student2 
print(age_student1)   # Output: 19

The dictionaries can be nested to any number of levels.


Some methods of the dictionary type

Extract keys: The method keys() is useful to extract only keys from the dictionary.  It is as follows.

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}

list_type = dict1.keys()  # returns dict_keys(['Python', 'Java', 'C++'])

Similarly, values of the dictionary can be extracted as follows.

Extract values: The method values() is useful to extract only values from the list. The following code lines illustrated the same.

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}
list_type = dict1.values()  # returns dict_values(['scientific', 'enterprise level', 'system level'])

Extract items: The method items() extracts the items (key-value pair) as illustrated in the following code lines.

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}
list_type = dict1.items()  

The output is as follows.
dict_items([('Python', 'scientific'), ('Java', 'enterprise level'), ('C++', 'system level')])

Dictionary to list conversion: The dictionary can be converted into a list using list() with a dictionary as an argument. The list consists of only keys. 

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}
lt = list(dict1)   #   The list is  ['Python', 'Java', 'C++'] 
If you want sorted keys (requirement in many situations), use the sorted() function on the created list

lt = sorted(lt)            # the sorted list is ['C++', 'Java', 'Python']

Observe that sorted is a general function in Python for sorting in ascending or descending order.

Deleting an item from the dictionary: The general del statement of Python is used to delete the key-value pair or the entire dictionary.

del dict1['C++']         # deletes the key value pair 'C++': 'system level'
print(dict1)                # prints  {'Python': 'scientific', 'Java': 'enterprise level'}

del dict1                    # deletes the entire dictionary
print(dict1)                # results in NameError

Avoid error using the get() method: While fetching the value for a key that does not exist, the interpreter ends the running of your script with an error. To avoid this and continue running the script, use the following get() method to access the value of the key.

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}
print(dict1.get('R', 'different'))

The key 'R' does not exist, the get() method returns the second argument ('different'). 

Adding key-value pair using the setdefault() method: This method is useful to add new key-value pairs to the existing dictionary.  But, if the key already exists in the dictionary, the method returns the value of that key. The following code illustrates the same.

dict1 = {'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level'}
dict1.setdefault('Matlab', ''prototype')
print(dict1)  

The dictionary dict1 is now,
{'Python': 'data science', 'Java': 'enterprise level', 'C++': 'system level', 'Matlab': 'prototype'}

Now, let us try to add the existing key to the dict1.

dict1.setdefault('Python', ''prototype')        # returns 'data science'

This method is useful to retain already existing key-value pairs.

Lists Vs Dictionaries

Feature List Dictionary
Definition            An ordered collection of items Collection of key–value pairs
Syntax       lt = [1, 2, 3] dict = {"a": 1, "b": 2}

Indexing

            by position; lt[0] 

By key; dict['a']

Order 

            Preserves insertion order

Preserves insertion order

Duplicates
            
            Allows duplicate values

Keys must be unique (values can duplicate)

Mutability
            
            Mutable (can change items)

Mutable (can change values, add/remove pairs)

Use case
            
            When order matters, 

When data is paired (label & value)






No comments:

Post a Comment