A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. A dictionary is an indexed data structure i.e. the contents of a dictionary can be accessed by using indexes, here in the dictionary, the key is used as an index. Here, the dict() function is used to create a new dictionary or convert other iterable objects into a dictionary. In this article, we will learn more about Python dict() function.
Python dict() Syntax
dict(**kwarg)
dict(iterable, **kwarg)
dict(mapping, **kwarg)
Parameters:
kwargs: It is a keyword argument.terable.
iterable: An iterable containing keyword arguments
mapping: It is another dictionary.
dict() Function in Python
dict() function is used to create a new dictionary or convert other iterable objects into a dictionary. Dictionaries in Python are collections of key-value pairs, and the dict() function allows us to create them in various ways.
Python dict() Function is used to create a Python dictionary, a collection of key-value pairs.
Python
dict(One = "1", Two = "2")
Output:
{'One': '1', 'Two': '2'}
Example 1: Creating dictionary using keyword arguments
We can pass keyword arguments as a parameter with the required values that will be keys and values of the dictionary.
Syntax:
dict(**kwarg)
Python
# passing keyword arguments to dict() method
myDict = dict(a=1, b=2, c=3, d=4)
print(myDict)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Example 2: Creating deep-copy of the dictionary using dict()
Creating a new instance (deep copy) of dictionary using dict().
Syntax:
dict(mapping)
Python
main_dict = {'a': 1, 'b': 2, 'c': 3}
# deep copy using dict
dict_deep = dict(main_dict)
# shallow copy without dict
dict_shallow = main_dict
# changing value in shallow copy will change main_dict
dict_shallow['a'] = 10
print("After change in shallow copy, main_dict:", main_dict)
# changing value in deep copy won't affect main_dict
dict_deep['b'] = 20
print("After change in deep copy, main_dict:", main_dict)
Output:
After change in shallow copy, main_dict: {'a': 10, 'b': 2, 'c': 3}
After change in deep copy, main_dict: {'a': 10, 'b': 2, 'c': 3}
Example 3: Creating dictionary using iterables
The keys and values can be passed to dict() in form of iterables like lists or tuples to form a dictionary and keyword arguments can also be passed to dict().
Syntax:
dict(iterable, **kwarg)
Python
# A list of key value pairs is passed and
# a keyword argument is also passed
myDict = dict([('a', 1), ('b', 2), ('c', 3)], d=4)
print(myDict)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Python dict() Function – FAQs
Why use dict in Python?
A dict (dictionary) is used for storing data in key-value pairs. It is highly efficient for lookups, insertions, and deletions due to its underlying hash table implementation. Dictionaries are versatile for managing data with unique identifiers and are dynamically resizable.
What does dict.items() do?
The dict.items() method returns a view object that displays a list of the dictionary’s key-value pairs. This view object is dynamic, meaning it updates when the dictionary changes.
Example:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
items = my_dict.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
Is dict() and {} the same?
No, dict() and {} are different ways to create dictionaries:
dict(): A constructor that can take keyword arguments, a list of tuples, or another dictionary.{}: A literal syntax used to create an empty dictionary or one with specified key-value pairs.
Example:
# Using dict() to create a dictionary
dict1 = dict(name='Alice', age=30)
# Using {} to create a dictionary
dict2 = {'name': 'Alice', 'age': 30}
Can we use dict() method to copy a dictionary?
Yes, you can use the dict() constructor to create a shallow copy of an existing dictionary. This method copies the dictionary but does not clone nested objects.
Example:
original_dict = {'name': 'Alice', 'age': 30}
copied_dict = dict(original_dict)
print(copied_dict) # Output: {'name': 'Alice', 'age': 30}
What type is dict.keys() in Python?
The dict.keys() method returns a view object of type dict_keys, which displays a dynamic view of all the dictionary’s keys. It reflects changes made to the dictionary.
Example:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
keys = my_dict.keys()
print(type(keys)) # Output: <class 'dict_keys'>
print(keys) # Output: dict_keys(['name', 'age', 'city'])
Similar Reads
Python Built in Functions
Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
6 min read
abs() in Python
The Python abs() function return the absolute value. The absolute value of any number is always positive it removes the negative sign of a number in Python. Example: Input: -29Output: 29Python abs() Function SyntaxThe abs() function in Python has the following syntax: Syntax: abs(number) number: Int
3 min read
Python - all() function
The Python all() function returns true if all the elements of a given iterable (List, Dictionary, Tuple, set, etc.) are True otherwise it returns False. It also returns True if the iterable object is empty. Sometimes while working on some code if we want to ensure that user has not entered a False v
3 min read
Python any() function
Python any() function returns True if any of the elements of a given iterable( List, Dictionary, Tuple, set, etc) are True else it returns False. Example Input: [True, False, False]Output: True Input: [False, False, False]Output: FalsePython any() Function Syntaxany() function in Python has the foll
5 min read
ascii() in Python
In Python, we have ascii() function that returns a string containing a printable representation of an object. In this article, we will see about ascii() in Python. Python ascii() FunctionPython ascii() function returns a string containing a printable representation of an object and escapes the non-A
3 min read
bin() in Python
Python bin() function returns the binary string of a given integer. bin() function is used to convert integer to binary string. In this article, we will learn more about Python bin() function. Example In this example, we are using the bin() function to convert integer to binary string. C/C++ Code x
2 min read
bool() in Python
Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure. Example C/C++ Code x = bool(1) print(x) y = bool() print(y) OutputTrue False What is the bool() Method in Python?bool() is a built-in function of Python pro
4 min read
Python bytes() method
bytes() method in Python is used to create a sequence of bytes. In this article, we will check How bytes() methods works in Python. [GFGTABS] Python a = "geeks" # UTF-8 encoding is used b = bytes(a, 'utf-8') print(b) [/GFGTABS]Outputb'geeks' Table of Content bytes() Method SyntaxUs
3 min read
chr() Function in Python
chr() function returns a string representing a character whose Unicode code point is the integer specified. chr() Example: C/C++ Code num = 97 print("ASCII Value of 97 is: ", chr(num)) OutputASCII Value of 97 is: a Python chr() Function Syntaxchr(num) Parametersnum: an Unicode code integer
3 min read
Python dict() Function
A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. A dictionary is an indexed data structure i.e. the contents of a dictionary can be accessed by using indexes, here in the dictionary, the key is used as an index. Here, the dict() function is used to create a n
4 min read