Open In App

Python Operators for Sets and Dictionaries

Last Updated : 11 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Following article mainly discusses operators used in Sets and  Dictionaries. Operators help to combine the existing value to larger syntactic expressions by using various keywords and symbols.

  1. Sets: Set class is used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {} and each element is separated by the comma(,) and it is mutable.

Example:

Python3




# set of alphabet
set = {'a', 'b', 'c', 'd', 'e'}
print(set)


Output:

{'c', 'b', 'd', 'e', 'a'}

        2. Frozensets: It is an immutable form of a set, used to form a set of the set.

         Sets and frozensets support the following operators:

  • key in s: It is used to check that the given key is in the set or not.
  • key not in s: it returns True if the key is not in the set.

Example:

Python3




s = {4, 5, 8, 6, 3, 2, 5}
key = 3
x = key in # containment check
y = key not in # non-containment check
print(x, y)


Output:

True False
  • s1 ==  s2 : To check s1 is equivalent to s2. i.e. all elements of s1 are in s2 and vice versa . it return True if  s1 is equivalent to s2.
  • s1 !=  s2 :  s1 is not equivalent to s2. i.e. at least one elements of s1 is not in s2. it return True if  s1 is not equivalent to s2.

Example:

Python3




s1 = {'t', 3, 6, 5, 7, 8, 4, 9}
s2 = {5, 7, 8, 9, 't', 4, 3, 6}
  
# equivalent check
x = s1 == s2
  
# non-equivalent check
y = s1 != s2
print(x)
print(y)


Output:

True
False

Comparison of sets is not lexicographic since sets don’t arrange their element in a proper order. Thus, s1 cannot be greater than or less than s2 and vice versa, rather, they can be subsets or supersets.

  • s1 <= s2  :  s1 is subset of s2. i.e. all elements of s1 are in s2, returns True if s1 is a subset of s2.
  • s1 < s2  :  s1 is proper subset of s2. i.e.  all elements of s1 are in s2  but all element of s2 are not necessarily  in s1, returns True if  s1 is a proper subset of s2.
  • s1 >= s2  : s1 is superset of s2. i.e. all elements of s2 are in s1, returns True if s1 is a superset of s2.
  • s1 > s2  : s1 is proper superset of s2. i.e. all elements of s2 are in s1  but all element of s1 are not necessarily in s2, returns True if s1 is a proper superset of s2.

Example :

Python3




s1 = {2, 5, 3, 7, 'c', 'a', 8}
s2 = {3, 7, 8, 'c'}
  
# subset check
w = s1 <= s2
  
# proper subset check
x = s1 < s2
  
# superset check
y = s1 >= s2
  
# proper superset check
z = s1 > s2
print(w, x, y, z)


Output:

False False True True
  • s1 | s2: union of s1 and s2, returns elements of both s1 and s2 without repetition.
  • s1 & s2: intersection of s1 and s2, returns elements which are present in both sets.
  • s1 − s2:  set difference, returns elements which are in s1 but not in s2.
  • s1 ˆ s2: the set of elements in precisely one of s1 or s2, returns elements which are in s1 but not in s2 and elements which in s2 but not in s1.

Example:

Python3




s1 = {2, 5, 3, 7, 'c', 'a', 8}
s2 = {3, 7, 8, 'c', 9, 11, 'd'}
  
# union
w = s1 | s2
  
# intersection
x = s1 & s2
  
# elements which are in s1 but not in s2
# and elements which are in s2 but not in s1
y = s1 ^ s2
  
# set difference
z = s1-s2
print(w)
print(x)
print(y)
print(z)


Output:

{2, 3, 5, ‘a’, 7, 8, 9, 11, ‘d’, ‘c’}

{8, ‘c’, 3, 7}

{2, 5, 9, ‘d’, 11, ‘a’}

{2, 5, ‘a’}

    3. Dictionaries: It is a mapping of different keys to its associated values. We use curly brackets { } to create dictionaries too. 

Example:

Python3




# Example of Dictionary
d = {'jupiter': 'planet', 'sun': 'star'}
print(d)


Output:

{'jupiter': 'planet', 'sun': 'star'}

Dictionaries support the following operators:

  • d[key]: it is used to get the value associated with the given key from the dictionary.
  • d[key] = value: it is used to set (or reset) the value associated with the given key from the dictionary.
  • del d[key]: It is used to delete the key and its associated value from the dictionary.

Example:

Python3




dict = {'math': 45, 'english': 60, 'science': 65
        'computer science': 70}
  
# retrieving value by using key
x = dict['science']
print(x)
  
# reassigning value
dict['english'] = 80
print(dict)
  
# deleting
del dict['math']
print(dict)


Output:

65
{‘math’: 45, ‘english’: 80, ‘science’: 65, ‘computer science’: 70}
{‘english’: 80, ‘science’: 65, ‘computer science’: 70}

  • key in d: It is used to check whether a certain key is in the dictionary or not. also called containment check. It returns a boolean value.
  • key not in d: It returns a boolean value, True if the key is not present in the dictionary, also called non-containment check

Example:

Python3




dict = {'math': 45, 'english': 60, 'science': 65,
        'computer science': 70}
  
# containment check
x = 'english' in dict
  
# non-containment check
y = 'hindi' not in dict
print(x)
print(y)


Output:

True
True
  • d1 == d2:  it compares key-value pair of both dictionaries, if found, returns True.
  • d1 != d2: it compares key-value pair of both dictionaries, if found returns True.

Example:

Python3




d1 = {'a': 5, 'b': 7, 'c': 9, 'e': 3}
d2 = {'c': 9, 'a': 5, 'b': 7, 'e': 3}
  
x = d1 == d2
y = d1 != d2
  
print(x)
print(y)


Output:

True
False

Dictionaries are similar to sets. they also don’t have any elements in a definite order.

The concept of subset and superset is not applicable on dictionaries. Thus, subset and superset operators are meaningless for it.



Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python Program to Find Duplicate sets in list of sets
Given a list of sets, the task is to write a Python program to find duplicate sets. Input : test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, {1, 4, 3}, {7, 8, 9}]Output : [frozenset({1, 4, 5, 6}), frozenset({1, 3, 4})]Explanation : {1, 4, 5, 6} is similar to {6, 4, 1, 5} hence part of result. Input : test_list = [{4, 5, 6, 9}, {6, 4, 1, 5}, {
8 min read
Filter List of Python Dictionaries by Key in Python
Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you're working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Py
3 min read
Python | Sort Python Dictionaries by Key or Value
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
7 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python program to divide dictionary and its keys into K equal dictionaries
Given a dictionary, divide it into an equal dictionary list of size k, by dividing each key's value. Input : test_dict = {"Gfg" : 9, "is" : 6, "best" : 12} , K = 3 Output : [{'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}] Explanation : Values distributed equally among dictionaries. I
3 min read
three90RightbarBannerImg