Python - dict() function
The Python dict() function (or dict() constructor) is used to create dictionary using an iterable object containing key-value pairs.
Syntax
dict(iterable)
Parameters
iterable |
Required. iterable with key-value pairs etc. |
Return Value
Returns a dictionary containing all elements of the passed arguments.
Example: Create dictionary using iterable with key-value pairs
In the example below, dict() function is used to create dictionary using iterables containing key-value pairs.
#using list of tuple as iterable #similarly list of lists and list of sets can be used MyList = [('name', 'John'), ('age', 25)] MyDict = dict(MyList) print(MyDict) #using tuple of lists as iterable #similarly tuple of tuples and tuple of sets can be used MyTuple = (['name', 'John'], ['age', 25]) MyDict = dict(MyTuple) print(MyDict) #using set of tuple as iterable MySet = {('name', 'John'), ('age', 25)} MyDict = dict(MySet) print(MyDict)
The output of the above code will be:
{'name': 'John', 'age': 25} {'name': 'John', 'age': 25} {'name': 'John', 'age': 25}
Create dictionary using keyword arguments:
It can also be created using keyword argument.
Syntax
dict(keyword arguments)
Parameters
keyword arguments |
Required. contain as many keyword argument like key = value, key = value ...etc |
Example: dict function using keyword argument
MyDict = dict(name='John', age=25) print(MyDict)
The output of the above code will be:
{'name': 'John', 'age': 25}
❮ Python Dictionary Methods