The dict() function is used to create a dictionary.Dictionary is an iterable where data are stored as key and value pairs
Example : Student_dict = {
name :"Ram"
age : 22
course : "Bachelors"
}
The dict() function can be used in three different ways
Bypassing keyword arguments only
dict(**kwargs) #where kwargs denotes keyword arguments of form key=value
Bypassing an iterable and keyword arguments
dict(iterable,**kwargs) #where iterable can be any iterable like a list
By Passing mapping and keyword arguments
dict(mapping,**kwargs) #where mapping is key to value pair mapping
Even if no parameter is passed to the dict function, it won't throw an error. It will return an empty dictionary if no parameter is passed.
Parameter | Description | Required / Optional |
---|---|---|
**kwargs | Any number of keyword arguments in form key=value separated by comma |
Required |
iterable | Any iterable in python | Optional |
Mapping | Key to value pair mapping | Optional |
The output of the dict function is always a dictionary. If no parameter is passed an empty dictionary is returned
Input | Return Value |
---|---|
None | Empty dictionary |
**kwargs | Converts the keyword arguments as a dictionary |
Iterable | Converts the iterable to the dictionary |
mapping | Converts the mapping to dictionary |
letters = dict(a=1, b=2)
print(' Letters dictionary is', letters)
print(type(letters))
Output:
Letters dictionary is {'a': 1, 'b': 2}
# iterable without keyword arguments
letters = dict((a,1), (b=2))
print(' letters dictionary is', letters)
print(type(letters))
# iterable with keyword arguments
letters = dict([('a',1), ('b',2)],c=3)
print(' letters dictionay is', letters)
print(type(letters))
Output:
letters dictionay is {'a': 1, 'b': 2}letters dictionay is {'a': 1, 'b': 2, 'c': 3}
# Mapping without keyword arguments
letters = dict({‘a’ : 1,’b’:2})
print(' letters dictionary is', letters)
print(type(letters))
# Mapping with keyword arguments
letters = dict({‘a’ : 1,’b’:2},c=3)
print(' letters dictionary is', letters)
print(type(letters))
Output:
letters dictionary is {'a': 1, 'b': 2}letters dictionary is {'a': 1, 'b': 2, 'c': 3}