Page Content

Tutorials

What Are Dictionaries And Sets In Python?

Dictionaries and Sets

Dictionaries and Sets
Dictionaries and Sets

For information organisation, Python has a number of built-in data types, such as sets and dictionaries. Unlike sequences like lists and tuples, these structures let you store and manipulate data in distinct ways.

Dictionaries

One essential Python feature is a dictionary, sometimes referred to as a dict. Data is stored in dictionaries according to their values rather than their location. Hash tables and associative arrays are other names for them. A collection of key value pairs is called a dictionary. Every dictionary key corresponds to a corresponding value. Comparable to a real dictionary, you search up a key to find its value; a word is the key, and its definition is the value.

Key characteristics of dictionaries include:

  • There is no order to them.
  • They can be altered or mutated.
  • Keys, not a range of numbers, are used to index them.
  • Within a dictionary, keys must be distinct.
  • It is acceptable to use duplicate values.
  • Diverse components are permitted.
  • Unlike sequences, they do not permit indexing and slicing.

You can create a dictionary in a couple of ways:

  • Putting key-value pairs inside curly braces {}. Key value pairs are separated by commas, and the key and its value are separated by a colon (:). {} stands for an empty dictionary
  • Using the constructor function dict(). This can be accomplished by giving a series of key-value pairs (such as a list of tuples), using keyword parameters, or by using an empty call dict() for an empty dictionary.

Working with dictionaries involves several basic operations:


  • Accessing values via the square bracket notation dictionary name[key] to access values via their keys. A Key Error is raised if the key is missing.

  • Adding new key-value pairs or modifying the value Using the same square bracket syntax dictionary name[key] = value, you can add new key-value pairs or change the value associated with an existing key. The value of the key is updated if it already exists; if not, a new key-value pair is added.
  • Deleting an item Using the del statement del dictionary name[key], an item can be deleted by key. Additionally, you can acquire an object by key and delete it using the pop() method. The last key value pair entered is eliminated using the popitem() method.
  • Getting all key-value pairs Using the items() method, keys with keys(), and values with values(), all key value pairs are obtained. View objects are returned by these.

You can loop through a dictionary in different ways using a for loop:

  • Looping through all key value pairs.
  • Looping through all the keys. By default, iterating over a dictionary directly traverses its keys.
  • Looping through all values.


Nested dictionaries might contain another dictionary or a list. This lets you store more complex, structured data.

# Example of a nested dictionary structure
life = {
    'animals': {
        'cats': ['Henri', 'Grumpy', 'Lucy'], 
        'octopi': {}, 
        'emus': {} 
    }, 
    'plants': {}, 
    'other': {} 
}

Other dictionary methods include update(D2), which combines dictionaries or updates with specified key-value pairs, and get(key, default), which returns the value for a key or a default value if the key cannot be located. The number of key-value pairs is returned by the len() function.

Sets

Another built-in Python data type is a set. Sets function similarly to mathematical sets. A collection of distinct values is called a set. A set should be used to represent a collection of distinct values as a single object.

Key characteristics of sets include:

  • It is not permitted to have duplicates.
  • The order of insertion is not maintained.
  • Slicing and indexing are ineffective.
  • Diverse components are permitted.
  • They can change.

A list of elements separated by commas can be enclosed in curly brackets to make a set, or you can use the set() constructor.

  • Using curly braces {} This uses the initial elements to create a set.
  • Using the set() constructor Since denotes an empty dictionary, this is used to create an empty set. Other iterable objects can likewise be converted to sets using it.

Common set operations and methods include:

  • Adding an item Using the add() method to add an item.
  • Deleting an item Using the delete() method to get rid of an item. An error will be raised if remove() is used on an item that is not in the set.
    Using the in operator to check for a value.
  • Testing for a value Using the clear() method to remove every item.
  • Getting the length Len() is used to obtain the length.
  • Performing combinations and operators Using operators and combinations such as symmetric difference (^), union (|), intersection (&), and difference (-). Additionally, there are functions like difference().
  • Testing for subsets Subset (issubset()) and superset (issuperset()) testing.

You can iterate through a set using a for loop:

An unchangeable version of a set is called a frozenset. Using frozenset(), you can produce an immutable set.
When it comes to removing elements and testing membership (in operator), sets are frequently more effective than lists. They are helpful for doing mathematical set operations and working with unique items. For instance, keeping keywords in storage for easy access.
Like list comprehensions, comprehensions can be used to generate dictionaries and sets.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index