Dict is not a sequence

In Python, a dictionary (dict) is not a sequence type like lists or tuples. Instead, it is an unordered collection of key-value pairs. Here’s a detailed explanation with examples:

  • Keys: A dictionary’s keys are unique and immutable objects, such as strings or numbers, that are used to retrieve corresponding values.
  • Values: Each key is associated with a value, which can be of any type and can be mutable or immutable.

To create a dictionary, we use curly braces {} and separate the key-value pairs using colons (:). Let’s see an example:

    
      my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
      print(my_dict)
    
  

The output will be:

    
      {'name': 'John', 'age': 25, 'city': 'New York'}
    
  

To access the value associated with a particular key, we can use square brackets [] along with the key. For example:

    
      print(my_dict['name'])
    
  

This will output:

    
      John
    
  

Dictionaries are mutable, so we can modify their values or add new key-value pairs. We can also delete items using the del keyword. Let’s illustrate this with an example:

    
      my_dict['age'] = 26  # modifying value
      my_dict['city'] = 'San Francisco'  # modifying value
      my_dict['job'] = 'Developer'  # adding new key-value pair
      del my_dict['city']  # deleting a key-value pair
      print(my_dict)
    
  

The updated dictionary will be:

    
      {'name': 'John', 'age': 26, 'job': 'Developer'}
    
  

Related Post

Leave a comment