Difference between python built-in dict(), set() and chr() function with practical example

Python dict()

Python dict() function is a constructor which creates a dictionary. Python dictionary provides three different constructors to create a dictionary:

  • If no argument is passed, it creates an empty dictionary.
  • If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
  • If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.

Python dict() Example

# Calling function  
result = dict() # returns an empty dictionary  
result2 = dict(a=1,b=2)  
# Displaying result  
print(result)  
print(result2)  

Output:

{}
{'a': 1, 'b': 2}

Python set() Function

In python, a set is a built-in class, and this function is a constructor of this class. It is used to create a new set using elements passed during the call. It takes an iterable object as an argument and returns a new set object.

Python set() Function Example

Calling function

result = set() # empty set  
result2 = set('12')  
result3 = set('javatpoint')  
# Displaying result  
print(result)  
print(result2)  
print(result3)  

Output:

set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}

Python chr() Function

Python chr() function is used to get a string representing a character which points to a Unicode code integer. For example, chr(97) returns the string ‘a’. This function takes an integer argument and throws an error if it exceeds the specified range. The standard range of the argument is from 0 to 1,114,111.

Python chr() Function Example

# Calling function  
result = chr(102) # It returns string representation of a char  
result2 = chr(112)  
# Displaying result  
print(result)  
print(result2)  
# Verify, is it string type?  
print("is it string type:", type(result) is str)  

Output:

ValueError: chr() arg not in range(0x110000)