C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python dict() FunctionPython dict() function is a constructor which creates a dictionary. Python dictionary provides three different constructors to a create dictionary.
Signaturedict ([**kwargs]) dict ([mapping, **kwargs]) dict ([iterable, **kwargs]) Parameterskwargs: It is a keyword argument. mapping: It is another dictionary. iterable: It is an iterable object in the form of a key-value pair(s). ReturnIt returns a dictionary. Let's see some examples of dict() function to understand it's functionality. Python dict() Function Example 1A simple example to create an empty or non-empty dictionary. Arguments of the dictionary are optional. # Python dict() function example # Calling function result = dict() # returns an empty dictionary result2 = dict(a=1,b=2) # Displaying result print(result) print(result2) Output: {} {'a': 1, 'b': 2} Python dict() Function Example 2# Python dict() function example # Calling function result = dict({'x': 5, 'y': 10}, z=20) # Creating dictionary using mapping result2 = dict({'x': 5, 'y': 10, 'z':20}) # Displaying result print(result) print(result2) Output: {'x': 5, 'z': 20, 'y': 10} {'x': 5, 'z': 20, 'y': 10} Python dict() Function Example 3# Python dict() function example # Calling function result = dict([(1, 'One'), [2, 'Two'], [3,'Three']]) # Creating using iterable result2 = dict([['x','X'],('y','Y')]) # Displaying result print(result) print(result2) Output: {1: 'One', 2: 'Two', 3: 'Three'} {'y': 'Y', 'x': 'X'}
Next TopicPython Functions
|