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:

  1. kwarg: key and value pair separated by a comma, e.g key='value'.
  2. iterable: An iterable containing keyword arguments
  3. mapping: A mapping object that maps key to value.

Return Value:

Returns a dict object.

The following example converts keyword arguements into dictionaries.

Example: Create Dictionary
emptydict = dict()
print(emptydict)

numdict = dict(I='one', II='two', III='three')
print(numdict)
Output
{'I': 'one', 'II': 'two', 'III': 'three'}

You cannot specify integers as keys as keyword arguments. It will give a syntax error.

Example: dict()
numdict = dict(1='one', 2='two', 3='three')
Output
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.

Example: dict()
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)

Output
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.

Example: dict()
numdict = dict({'I':'one', 'II':'two', 'III':'three'}) # using list of tuple
print(numdict)
Output
{'I': 'one', 'two': 'II', 'III': 'three'}
Want to check how much you know Python?