Skip to content

Dictionaries & Sets

A dictionary in Python is an unordered, mutable collection of items where each item is a key-value pair. The keys must be unique and immutable (like strings or numbers), while the values can be of any data type. Dictionaries are defined using curly braces {}.


You create a dictionary by placing key-value pairs inside curly braces, with a colon separating each key from its value.

person = {
"name": "Akash",
"age": 20,
"profession": "Full Stack Web Developer",
"programmer": True
}
print(type(person), "\n", person)
# OUTPUT:
# <class 'dict'>
# {'name': 'Akash', 'age': 20, 'profession': 'Full Stack Web Developer', 'programmer': True}

You can access dictionary values using either square brackets or the get() method.

  1. Using Square Brackets []: This method is a direct way to retrieve a value using its key. If the key does not exist, it will raise a KeyError.

    print(person["name"]) # Output: Akash
  2. Using the get() Method: The get() method is a safer way to access a value. It returns None if the key is not found, or a default value you specify, which prevents a KeyError.

    print(person.get("name")) # Output: Akash
    print(person.get("marks", "Not Found")) # Output: Not Found

To add a new key-value pair or modify an existing one, use square brackets and assign a new value.

person = {
"name": "Akash",
"age": 20,
"profession": "Full Stack Web Developer",
"programmer": True
}
# Adding a new key-value pair
person["city"] = "New York"
# Updating an existing key
person["age"] = 20
print(person)
# Output: {'name': 'Akash', 'age': 20, 'profession': 'Full Stack Web Developer', 'programmer': True, 'city': 'New York'}

There are several methods for removing items from a dictionary.

  • pop(key): Removes the specified key and returns its value.
  • popitem(): Removes and returns the last key-value pair added to the dictionary.
  • del Statement: Deletes a specific key or the entire dictionary.
  • clear(): Removes all items, leaving an empty dictionary.
# Using pop()
age = person.pop("age")
print(age) # Output: 20
# Using popitem()
last_item = person.popitem()
print(last_item) # Output: ('city', 'New York')
# Using del
del person["profession"]
print(person) # Output: {'name': 'Akash', 'programmer': True}
# Using clear()
person.clear()
print(person) # Output: {}

You can iterate through a dictionary’s keys, values, or both simultaneously.

  • Looping through keys:

    for key in person.keys():
    print(key)
  • Looping through values:

    for val in person.values():
    print(val)
  • Looping through both keys & values using items():

    for key, val in person.items():
    print(key, val, sep=" :: ")

  1. keys(): Returns a view object of all the keys.

    print(person.keys()) # Output: dict_keys(['name', 'age', 'profession', 'programmer'])
  2. values(): Returns a view object of all the values.

    print(person.values()) # Output: dict_values(['Akash', 20, 'Full Stack Web Developer', True])
  3. items(): Returns a view object of all key-value pairs as tuples.

    print(person.items()) # Output: dict_items([('name', 'Akash'), ('age', 20), ...])
  4. copy(): Creates a shallow copy of the dictionary.

    cpy_person = person.copy()
    print(cpy_person) # Output: {'name': 'Akash', ...}
  5. update(): Updates the dictionary with key-value pairs from another dictionary or iterable.

    person.update({"city": "New York", "country": "India"})
    print(person) # Output: {'name': 'Akash', ..., 'city': 'New York', 'country': 'India'}

A set is an unordered, mutable collection of unique elements. Sets are useful for tasks that require eliminating duplicate entries and for performing mathematical operations like unions and intersections. Because they are unordered, sets do not support indexing.


You can create a set using curly braces {} or the set() constructor.

fruits = {"apple", "banana", "cherry"}
print(type(fruits), "\n", fruits)
# Output:
# <class 'set'>
# {'banana', 'apple', 'cherry'}

It’s important to note that an empty curly brace {} creates an empty dictionary, not an empty set. To create an empty set, you must use set().

empty_set = set()
single_item_set = {1,}

Since sets are unordered, you cannot access elements using an index. You must use a for loop to iterate through the items.

Adding Items:

  • add(): Adds a single element to the set.
  • update(): Adds multiple elements from an iterable (like a list) to the set.
fruits = {"apple", "banana"}
fruits.add("orange")
fruits.update(["mango", "grape"])
print(fruits)
# Output: {'apple', 'banana', 'orange', 'mango', 'grape'}

There are several methods for removing items from a set:

  • remove(): Removes an item and raises a KeyError if it doesn’t exist.
  • discard(): Removes an item without raising an error if it’s not present.
  • pop(): Removes and returns a random element from the set.
  • clear(): Removes all elements from the set, leaving it empty.
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana") # Works fine
fruits.discard("grape") # No error, as 'grape' isn't there
print(fruits) # Output: {'apple', 'cherry'}

Sets are highly efficient for mathematical operations. You can use operators or built-in methods.

OperationOperatorMethodDescription
Union|.union()All unique elements from both sets.
Intersection&.intersection()Elements common to both sets.
Difference-.difference()Elements in the first set but not the second.
Symmetric Difference^.symmetric_difference()Elements in either set, but not both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1 & set2) # Output: {3}
# Difference
print(set1 - set2) # Output: {1, 2}
# Symmetric Difference
print(set1 ^ set2) # Output: {1, 2, 4, 5}

  • copy(): Creates a shallow copy of the set.
  • isdisjoint(): Checks if two sets have no elements in common.
  • issubset(): Checks if all elements of one set are present in another.
  • issuperset(): Checks if a set contains all elements of another set.
set1 = {1, 2}
set2 = {1, 2, 3}
print(set1.issubset(set2)) # Output: True
print(set2.issuperset(set1)) # Output: True

The above sets methods are the methods which are used mostly by python programmers.

There are a whole lot of other methods that python provides which can always be referred from the python docs: Python Sets Methods