Advanced Operations on Dictionaries in Python

05 min read

First, let us discuss a few important features of dictionaries:

  1. Dictionary items values have no specified restrictions. They can be any random Python object, either well-defined or an user-defined object. However, keys have a few specified restrictions:
  2. Keys must be unique to each of the items in a dictionary. No two items can have the same key. If a duplicate key is encountered in the dictionary, the last key is considered for operations.
  3. Strings, numbers or tuples can be used as keys in a dictionary, however, u cannot use mutable elements as keys.  

Now, let us discuss more on different common inbuilt functional operations that can be performed on dictionaries.

  • cmp(dict1,dict2)

Compares the defined items in both the lists.

  • len(dict1)

Returns the length of the dictionary or the number of items inside a given dictionary at that particular point in time.

  • str(dict1)

Returns a printable representation of the given dictionary

  • type(dict1)

Returns indicating the user that the variable passed as a parameter in type function is a dictionary type variable.

  • dict1.clear()                                            # clears all the elements in the dictionary and makes it an empty dictionary
  • dict1.copy()                                            # copies all the elements in dict1 to a variable which can later be used for further operations
  • dict1.get(key, default=None)      # returns the value of the key given by the user, else returns none if key not available in the given dictionary dict1
  • dict1.has_key(key)                            # returns True if the key given by the user is present in dict1. This condition can be used in 'if' conditional statements for various purposes.
  • dict1.items()                                        # returns all the tuple values (key, value) in the dictionary
  • dict1.keys()                                          # returns all the keys inside dict1 assigned to different items.
  • dict1.update(dict2)                        # Adds dictionary dict2's key-values pairs to dict1
  • dict1.values()                                     # returns only the dictionary values inside dict1 assigned to unique keys. 
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error