Python dict() Method
The dict()
method creates a dictionary object from the specified keys and values, or iterables of keys and values or mapping objects.
Syntax:
dict(**kwarg)
dict(iterable, **kwarg)
dict(mapping, **kwarg)
Parameters:
- kwarg: key and value pair separated by a comma, e.g key='value'.
- iterable: An iterable containing keyword arguments
- mapping: A mapping object that maps key to value.
Return Value:
Returns a dict object.
The following example converts keyword arguements into dictionaries.
emptydict = dict()
print(emptydict)
numdict = dict(I='one', II='two', III='three')
print(numdict)
{'I': 'one', 'II': 'two', 'III': 'three'}
You cannot specify integers as keys as keyword arguments. It will give a syntax error.
numdict = dict(1='one', 2='two', 3='three')
SyntaxError: keyword can't be an expression
A list, set, or a tuple containing keys and values can also be used to create a dictionary where integers can be keys.
numdict = dict([(1,'one'),(2,'two'),(3,'three')]) # using list of tuple
print("dict1 = ", numdict)
numdict = dict([{'I', 'one'}, {'II', 'two'}, {'III', 'three'}]) # using list of set
print("dict2 = ", numdict)
numdict = dict({(1,'one'),(2,'two'),(3,'three')}) # using set of tuples
print("dict3 = ", numdict)
dict1 = {1: 'one', 2: 'two', 3: 'three'}
dict2 = {'I': 'one', 'two': 'II', 'III': 'three'}
dict3 = {1: 'one', 2: 'two', 3: 'three'}
The following creates a dictionary by passing mapping object.
numdict = dict({'I':'one', 'II':'two', 'III':'three'}) # using list of tuple
print(numdict)
{'I': 'one', 'two': 'II', 'III': 'three'}