Python Dictionary Methods

Posted in /  

Python Dictionary Methods
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    A Dictionary is a Python inbuilt data structure that store the items in the form of key:value pairs. The dictionary data structure is similar to the hash table, where it maps a key to a value. Dictionary keys can only be an immutable Python data type such as int, float, string, or tuple, and a value could be any data object.

    Dictionary is a built-in data object, and it comes with many methods. A dictionary method is a function that we can call on a dictionary object to perform some operation. In this Python guide, we will discuss all the dictionary methods that are available in Python3.  Before that, let's have a brief introduction to the Python dictionary.

    Python Dictionary Overview

    Python Dictionary is a built-in data structure that collects data values as key:value pairs. To initialize a dictionary, we can either use the curly brackets {} , or the dict() function.

    Dictionary initialization with curly brackets

    #dictionary initialization with curly brackets
    students = {"1":"Rajesh", "2":"Raj", "3":"Aman"}
    
    print(students)    #{'1': 'Rajesh', '2': 'Raj', '3': 'Aman'}

    Dictionary initialization with dict function

    #dictionary initialization with dict function
    students = dict(
                    (
                        ("1", "Rajesh"),
                        ("2","Raj"),
                        ("3","Aman")
                    )
                   )
    
    print(students)    # {'1': 'Rajesh', '2': 'Raj', '3': 'Aman'}

    Access A dictionary

    To access a specific dictionary value, we use the value's corresponding key name.

    Example

    students = {"1":"Rajesh", "2":"Raj", "3":"Aman"}
    
    #Access dictionary values 
    print("Student 1:",students["1"])

    Output

    Student 1: Rajesh

    If we try to access a dictionary value with an invalid key, we receive the KeyError.

    Example

    students = {"1":"Rajesh", "2":"Raj", "3":"Aman"}
    
    #Access dictionary values with invalid key
    print("Student 1:",students[1])

    Output

    Traceback (most recent call last):
      File "main.py", line 4, in 
        print("Student 1:",students[1])
    KeyError: 1

    Python Dictionary Methods

    Now Let's discuss the different methods available for a dictionary object. Python dictionary supports 11 normal methods.

    1. clear()
    2. copy()
    3. fromkeys()
    4. get()
    5. items()
    6. keys()
    7. pop()
    8. popitem()
    9. setdefault()
    10. update()
    11. values()

    1. Python dictionary clear() method

    With the dictionary clear() method we can remove all the key-value pairs or items from the dictionary.

    syntax

    dictionary_name.clear()

    return

    The clear() method perform the in-place operation and return the None

    argument

    It does not accept any argument value.

    Example

    students = {"1":"Rajesh", "2":"Raj", "3":"Aman"}
    
    #remove all items from the dictionary
    students.clear()
    
    print(students)    # {}

    2. Python dictionary copy() method

    The copy method creates a shallow copy of the dictionary and returns that copied dictionary. By shallow copy means, if the dictionary has reference objects like a nested dictionary or list, the copy() method will only copy their reference. To know more about Python's shallow and deep copy, click here .

    syntax

    dictionary_name.copy()

    return

    The copy method returns a shallow copy of the dictionary.

    argument

    The copy() method does not accept any argument.

    Example

    students = {"1":"Rajesh", "2":"Raj", "3":"Aman"}
    
    #copy the dictionary
    copied_data = students.copy()
    
    #change in copied data
    copied_data["1"] = "Rahul"
    
    print("Actual Data:", students)
    print("Copied Data:", copied_data)

    3. Python dictionary fromkeys() method

    Using the dictionary fromkeys() method, we can create a new dictionary with multiple keys and a single value.

    syntax

    dictionary_name.formkeys(keys_sequence, value=None)

    return

    The fromkeys() method creates and returns a new dictionary object.

    arguments

    It can accept two arguments values

    1. keys_sequence: An Iterable object which we want to set as the keys for the new dictionary.
    2. value(optional): It is the value that will be assigned to every new key. By default, its value is None.

    Example

    nums = dict()
    
    even = [2,4,6,8,10]
    
    #new dictionary with even keys
    even_nums = nums.fromkeys(even, "Evan value")
    
    print("Even Nums Dictionary:\n", even_nums)

    output

    Even Nums Dictionary:
    {2: 'Evan value', 4: 'Evan value', 6: 'Evan value', 8: 'Evan value', 10: 'Evan value'}

    The fromkeys() method is generally used when we want to initialize a dictionary with keys and a default value.

    4. Python dictionary get() method

    The get method accepts a key name and returns the value associated with that key. The get method is error-free and returns None if the key is not present in the dictionary.

    syntax

    dictionary_name.get(key, value=None)

    return

    If the key is valid, it returns the value that corresponds to the specified key. Otherwise, return the None or the value species to the value argument.

    arguments

    The get method can accept two arguments.

    1. key: The key name which value we want to find.
    2. value (optional): The default value if the key does not present in the dictionary.

    Example

    marks = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #get rohan marks
    rohan_marks = marks.get("Rohan")
    
    print("Rohan Marks", rohan_marks)

    output

    Rohan Marks 900

    If the specified key is not present in the dictionary, the get() method returns the None or the value passed in the value argument.

    Example

    marks = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #get rohan marks
    sam_marks = marks.get("Sam", "key does not exist")
    
    print("Sam Marks:", sam_marks)

    Output

    Sam Marks: key does not exist

    5. Python dictionary items() method

    With the items() method, we can get all the items of the dictionary as a tuple pair of (key, value). This method is generally used when we want to access the key and values of a dictionary at the same time.

    syntax

    dictionary_name.items()

    return

    It returns an iterable object similar to a list (but not a list) that contains the tuple pairs of (key, values).

    argument

    The items() method does not accept any argument.

    Example

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    print("Names\t|\tMarks")
    print("-"*22)
    for name, mark in students.items():
        print(name, "\t|\t", mark)

    Output

    Names	|	Marks
    ----------------------
    Rahul 	|	 938
    Rohan 	|	 900
    Jay 	|	 983
    Sobha 	|	 849

    6. Python dictionary keys() method

    If you want to access all the keys from a dictionary, you can use the keys() method. The keys() method returns all the keys present in the dictionary.

    Syntax

    dictionary_name.keys()

    return

    It returns a list-like object dict_keys([]) , containing all the keys names.

    argument

    The keys() method does not accept any argument.

    Example

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #get all keys
    names = students.keys()
    
    print(names)

    Output

    dict_keys(['Rahul', 'Rohan', 'Jay', 'Sobha'])

    7. Python dictionary pop() method

    The pop() method accepts a key name as an argument and removes that key:value pair from the dictionary. With this method, we can remove a specific item from the dictionary.

    syntax

    dictionary_name.pop(key[,default])

    return

    It returns the value for the removed key:value pair if the key is present in the dictionary. If the key is not present in the dictionary, it returns the KeyError or the value specified to the default argument.

    argument

    The pop() method can accept two arguments

    1. key: The key which we want to remove.
    2. default(optional): The return value if the key does not present in the dictionary.

    Example

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #remove Sobha
    students.pop("Sobha")
    
    print(students)  #{'Rahul': 938, 'Rohan': 900, 'Jay': 983}

    8. Python dictionary popitem() method

    The popitem() can remove the last item from the dictionary. It removes the item and returns it as a tuple pair (key, value).

    syntax

    dictionary_name.popitem()

    return

    It returns a tuple pair (key,value) for the removed key:value item.

    argument

    The popitem() does not accept any argument value.

    Example

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #remove the last item
    removed_item = students.popitem()
    
    print("The removed item is:", removed_item)

    Output

    The removed item is: ('Sobha', 849)

    9. Python dictionary setdefault() method

    The setdefault(key[,default_value]) method will return the key value if the key is present in the dictionary. If the key is not in the dictionary, the setdefault() method inserts the key and the default_value into the dictionary and returns the default value.

    syntax

    dictionary_name.setdefault(key[,default_value])

    return

    It returns the value for the specified key.

    argument

    The setdefault(key[,default_value]) method accept two arguments.

    1. key: The key name that we need to search in the dictionary.
    2. default_value(optional)(None by default): The default value for the key that is not in the dictionary.

    Example (Get value with setdefault)

    we can use the setdefault() method to get the value for a key or to insert a new key-value pair.

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #get value with set default method
    rahul_marks = students.setdefault("Rahul")
    
    print("Rahul Marks:", rahul_marks)

    Output

    Rahul Marks: 938

    Example(Insert a value with setdefault)

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    #insert value with set default method
    students.setdefault("Sam", 909)
    
    print(students)

    Output

    {'Rahul': 938, 'Rohan': 900, 'Jay': 983, 'Sobha': 849, 'Sam': 909}

    10. Python dictionary update() method

    The update() method can insert new key:value pairs in an existing dictionary object. We can use this method to concatenate two dictionaries.

    syntax

    dictionary_name.update(iterable)

    return

    It performs the in-place operation and returns None.

    argument

    It can accept an iterable object, which could be a dictionary or an iterable object with key, and value pairs.

    Example

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    new_students = {"Sam":983, "Gourav":985}
    
    #insert the new students items in students
    students.update(new_students)
    
    print(students)

    Output

    {'Rahul': 938, 'Rohan': 900, 'Jay': 983, 'Sobha': 849, 'Sam': 983, 'Gourav': 985}

    11. Python dictionary values() method

    To get all the values from a dictionary, we can use the values() method. The values method returns a list like an iterable object containing all the values from the dictionary.

    syntax

    dictionary_name.values()

    return

    It returns a dict_values() iterable object with all the dictionary values.

    argument

    The values() method does not accept any argument.

    Example

    students = {"Rahul":938, "Rohan":900, "Jay":983, "Sobha":849}
    
    values = students.values()
    
    print(values)

    Output

    dict_values([938, 900, 983, 849])

    Final Thoughts

    Dictionary data structure is often used when we want to implement algorithms that use hash tables. The Python dictionary also makes it easy to work with JSON data and so on; there are many other real uses of a Python dictionary.

    In this Dictionary guide, we discussed all the methods available for a dictionary object in Python. The methods like clear(),  and update() perform the in-place operation and return None, the methods copy(), formkeys(), get(), items(), keys(), and values() do not change anything in the actual dictionary object and return a value. And the method pop() and popitems() and setdefault() methods perform the in-palce operation and also return some values.

    People are also reading:

    Leave a Comment on this Post

    0 Comments