dict() Function in Python:
The dict() function is used to create a dictionary.
A dictionary is an unordered, changeable, and indexed collection.
Syntax:
dict(keyword arguments)
Parameters
keyword arguments: This is Required. You can use as many keyword arguments as you want, separated by a comma: key = value, key = value…
Return Value:
dict() does not return any results (returns None).
Examples:
Example1:
Input:
Given key-value pairs = (emp_name="sunny", emp_id=2122, jobrole="software developer")
Output:
The result dictionary is : {'emp_name': 'sunny', 'emp_id': 2122, 'jobrole': 'software developer'}
Example2:
Input:
Given key-value pairs = (one="hello", two="good", three="morning")
Output:
The result dictionary is : {'one': 'hello', 'two': 'good', 'three': 'morning'}
dict() Function with Examples in Python
Method #1: Using Built-in Functions (Static Input)
Approach:
- Pass some random key-value pairs as the arguments to the dict() function and store it in a variable.
- Print the above result.
- The Exit of the Program.
Below is the implementation:
# Pass some random key-value pairs as the arguments to the dict() function # and store it in a variable. rslt = dict(emp_name="sunny", emp_id=2122, jobrole="software developer") # Print the above result print("The result dictionary is :") print(rslt)
Output:
The result dictionary is : {'emp_name': 'sunny', 'emp_id': 2122, 'jobrole': 'software developer'}
Method #2: Using Built-in Functions (User Input)
Approach:
- Take a dictionary and initialize it with an empty dictionary using dict() or {}.
- Give the number of keys as user input using int(input()) and store it in a variable.
- Loop till the given number of keys using for loop.
- Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
- Initialize the key with the value of the dictionary.
- Print the above-given dictionary.
- The Exit of the Program.
Below is the implementation:
# Take a dictionary and initialize it with an empty dictionary using dict() or {}. gvn_dict = dict() # Give the number of keys as user input using int(input()) and store it in a variable. numb_of_kys = int( input('Enter some random number of keys of the dictionary = ')) # Loop till the given number of keys using for loop. for p in range(numb_of_kys): # Inside the for loop scan the key and value as # user input using input(),split() functions # and store them in two separate variables. keyy, valuee = input( 'Enter key and value separated by spaces = ').split() # Initialize the key with the value of the dictionary. gvn_dict[keyy] = valuee print("The result dictionary is :") print(gvn_dict)
Output:
Enter some random number of keys of the dictionary = 3 Enter key and value separated by spaces = one hello Enter key and value separated by spaces = two good Enter key and value separated by spaces = three morning The result dictionary is : {'one': 'hello', 'two': 'good', 'three': 'morning'}