

{"id":5646,"date":"2018-01-03T11:33:30","date_gmt":"2018-01-03T06:03:30","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=5646"},"modified":"2026-04-21T14:16:58","modified_gmt":"2026-04-21T08:46:58","slug":"python-dictionary","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-dictionary\/","title":{"rendered":"Python Dictionary with Methods, Functions and Dictionary Operations"},"content":{"rendered":"<p>In the last few lessons, we have learned about some Python constructs like lists and tuples. Today, we will have a word about Python dictionaries, which is another type of data structure in Python.<\/p>\n<p>Moreover, we will study how to create, access, delete, and reassign a dictionary in Python. Along with this, we will learn Python dictionary methods and operations.<\/p>\n<p>So, let&#8217;s start the Python Dictionary Tutorial.<\/p>\n<h3>What are Python Dictionaries?<\/h3>\n<p>A real-life dictionary holds words and their meanings. As you can imagine, likewise, a Python dictionary holds key-value pairs.<\/p>\n<p>Let\u2019s look at how to create one.<\/p>\n<h3>How to Create a Dictionary in Python?<\/h3>\n<p>Creating a Dictionary is as easy as pie. Separate keys from values with a colon(:), and pairs from another by a comma(,). Finally, put it all in curly braces.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; {'PB&amp;J':'Peanut Butter and Jelly','PJ':'Pajamas'}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{&#8216;PB&amp;J&#8217;: &#8216;Peanut Butter and Jelly&#8217;, &#8216;PJ&#8217;: &#8216;Pajamas&#8217;}<\/div>\n<p>Optionally, you can put the dictionary in a variable. If you want to use it later in the program, you must do this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; lingo={'PB&amp;J':'Peanut Butter and Jelly','PJ':'Pajamas'}<\/pre>\n<p>To create an empty dictionary, simply use curly braces and then assign it to a variable<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict2={}\r\n&gt;&gt;&gt; dict2<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{}<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; type(dict2)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&lt;class &#8216;dict&#8217;&gt;<\/div>\n<h4>1. Python Dictionary Comprehension<\/h4>\n<p>You can also create a Python dict using comprehension. This is the same thing that you\u2019ve learned in your math class.<\/p>\n<p>To do this, follow an expression pair with a for-statement loop in python. Finally, put it all in curly braces.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; mydict={x*x:x for x in range(8)}\r\n&gt;&gt;&gt; mydict<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}<\/div>\n<p>In the above code, we created a Python dictionary to hold squares of numbers from 0 to 7 as keys, and numbers 0-1 as values.<\/p>\n<h4>2. Dictionaries with mixed keys<\/h4>\n<p>It isn\u2019t necessary to use the same kind of keys (or values) for a dictionary in Python.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict3={1:'carrots','two':[1,2,3]}\r\n&gt;&gt;&gt; dict3<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: &#8216;carrots&#8217;, &#8216;two&#8217;: [1, 2, 3]}<\/div>\n<p>As you can see here, a key or a value can be anything from an integer to a list.<\/p>\n<h4>3. dict() function in Python<\/h4>\n<p>Using the dict() function, you can convert a compatible combination of constructs into a Python dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict(([1,2],[2,4],[3,6]))<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 2, 2: 4, 3: 6}<\/div>\n<p>However, this function takes only one argument. So if you pass it three lists, you must pass them inside a list or a tuple. Otherwise, it throws an error.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict([1,2],[2,4],[3,6])<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#121&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>dict([1,2],[2,4],[3,6])<\/p>\n<p>TypeError: dict expected at most 1 arguments, got 3<\/p>\n<\/div>\n<h4>4. Declaring one key more than once in the dictionary<\/h4>\n<p>Now, let\u2019s try declaring one key more than once and see what happens.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; mydict2={1:2,1:3,1:4,2:4}\r\n&gt;&gt;&gt; mydict2<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 4, 2: 4}<\/div>\n<p>As you can see, 1:2 was replaced by 1:3, which was then replaced by 1:4. This shows us that a dictionary cannot contain the same key twice.<\/p>\n<h4>5. Declaring an empty dictionary and adding elements later<\/h4>\n<p>When you don\u2019t know what key-value pairs go in your Python dictionary,\u00a0 you can just create an empty Python dict, and add pairs later.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; animals={}\r\n&gt;&gt;&gt; type(animals)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&lt;class &#8216;dict&#8217;&gt;<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; animals[1]='dog'\r\n&gt;&gt;&gt; animals[2]='cat'\r\n&gt;&gt;&gt; animals[3]='ferret'\r\n&gt;&gt;&gt; animals<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: &#8216;dog&#8217;, 2: &#8216;cat&#8217;, 3: &#8216;ferret&#8217;}<\/div>\n<p>Any query on Python Dictionary yet? Leave a comment.<\/p>\n<h3>How to Access a Python Dictionary?<\/h3>\n<h4>1. Accessing the entire Python dictionary<\/h4>\n<p>To get the entire dictionary at once, type its name in the shell.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict3<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: &#8216;carrots&#8217;, &#8216;two&#8217;: [1, 2, 3]}<\/div>\n<h4>2. Accessing a value in the dictionary<\/h4>\n<p>To access an item from a list or a tuple, we use its index in square brackets. This is the python syntax to be followed. However, a Python dictionary is unordered. So to get a value from it, you need to put its key in square brackets.<\/p>\n<p>To get the square root of 36 from the above dictionary, we write the following code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; mydict[36]<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">6<\/div>\n<h4>3. get() function in python<\/h4>\n<p>The Python dictionary get() function takes a key as an argument and returns the corresponding value.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; mydict.get(49)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">7<\/div>\n<h4>4. When the Python dictionary key doesn\u2019t exist<\/h4>\n<p>If the key you\u2019re searching for doesn\u2019t exist, let\u2019s see what happens.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; mydict[48]<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#125&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>mydict[48]<\/p>\n<p>KeyError: 48<\/p>\n<\/div>\n<p>Using the key in square brackets gives us a KeyError. Now let\u2019s see what the get() method returns in such a situation.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; mydict.get(48)\r\n&gt;&gt;&gt;<\/pre>\n<p>As you can see, this didn\u2019t print anything. Let\u2019s put it in the print statement to find out what\u2019s going on.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; print(mydict.get(48))<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">None<\/div>\n<p>So we see, when the key doesn\u2019t exist, the get() function returns the value None. We discussed it earlier, and know that it indicates an absence of value.<\/p>\n<h3>Reassigning a Python Dictionary<\/h3>\n<p>The Python dictionary is mutable. This means that we can change it or add new items without having to reassign all of it.<\/p>\n<h4>1. Updating the Value of an Existing Key<\/h4>\n<p>If the key already exists in the Python dictionary, you can reassign its value using square brackets.<\/p>\n<p>Let\u2019s take a new Python dictionary for this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4={1:1,2:2,3:3}<\/pre>\n<p>Now, let\u2019s try updating the value for key 2.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4[2]=4\r\n&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 1, 2: 4, 3: 3}<\/div>\n<h4>2. Adding a new key to the dictionary<\/h4>\n<p>However, if the key doesn\u2019t already exist in the dictionary, then it adds a new one.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4[4]=6\r\n&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 1, 2: 4, 3: 3, 4: 6}<\/div>\n<p>Python dictionary cannot be sliced.<\/p>\n<h3>How to Delete a Python Dictionary?<\/h3>\n<p>You can delete an entire dictionary. Also, unlike a tuple, a Python dictionary is mutable. So you can also delete a part of it.<\/p>\n<h4>1. Deleting an entire Python dictionary<\/h4>\n<p>To delete the whole Python dict, simply use its name after the keyword \u2018del\u2019.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; del dict4\r\n&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#138&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>dict4<\/p>\n<p>NameError: name &#8216;dict4&#8217; is not defined<\/p>\n<\/div>\n<h4>2. Deleting a single key-value pair in a dictionary<\/h4>\n<p>To delete just one key-value pair, use the keyword \u2018del\u2019 with the key of the pair to delete.<\/p>\n<p>Now, let\u2019s first reassign dict4 for this example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4={1:1,2:2,3:3,4:4}<\/pre>\n<p>Now, let\u2019s delete the pair 2:2<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; del dict4[2]\r\n&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 1, 3: 3, 4: 4}<\/div>\n<p>A few other methods allow us to delete an item from a dictionary in Python. We will see those in section 8.<\/p>\n<h3>Built-in Functions on a Python Dictionary<\/h3>\n<p>A function is a procedure that can be applied to a construct to get a value. Furthermore, it doesn\u2019t modify the construct. Python gives us a few functions that we can apply to a Python dictionary. Take a look.<\/p>\n<h4>1. len() function in dictionary<\/h4>\n<p>The len() function returns the length of the dictionary in Python. Every key-value pair adds 1 to the length.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; len(dict4)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">3<\/div>\n<p>An empty Python dictionary has a length of 0.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; len({})<\/pre>\n<h4>2. any() function in dictionary<\/h4>\n<p>Like it is with lists an tuples, the any() function returns True if even one key in a dictionary has a Boolean value of True.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; any({False:False,'':''})<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">False<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; any({True:False,\"\":\"\"})<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">True<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; any({'1':'','':''})<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">True<\/div>\n<h4>3. all() function in dictionary<\/h4>\n<p>Unlike the any() function, all() returns True only if all the keys in the dictionary have a Boolean value of True.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; all({1:2,2:'',\"\":3})<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">False<\/div>\n<h4>4. sorted() function in dictionary<\/h4>\n<p>Like it is with lists and tuples, the sorted() function returns a sorted sequence of the keys in the dictionary. The sorting is in ascending order, and doesn\u2019t modify the original Python dictionary.<\/p>\n<p>But to see its effect, let\u2019s first modify dict4.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4={3:3,1:1,4:4}<\/pre>\n<p>Now, let\u2019s apply the sorted() function on it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; sorted(dict4)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">[1, 3, 4]<\/div>\n<p>Now, let\u2019s try printing the dictionary dict4 again.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{3: 3, 1: 1, 4: 4}<\/div>\n<p>As you can see, the original Python dictionary wasn\u2019t modified.<\/p>\n<p>This function returns the keys in a sorted list. To prove this, let\u2019s see what the type() function returns.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; type(sorted(dict4))<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&lt;class &#8216;list&#8217;&gt;<\/div>\n<p>This proves that sorted() returns a list.<\/p>\n<h3>Built-in Methods on a Python Dictionary<\/h3>\n<p>A method is a set of instructions to execute on a construct, and it may modify the construct. To do this, a method must be called on the construct. Now, let\u2019s look at the available methods for dictionaries.<\/p>\n<p>Let\u2019s use dict4 for this example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{3: 3, 1: 1, 4: 4}<\/div>\n<h4>1. keys() in dictionary<\/h4>\n<p>The keys() method returns a list of keys in a Python dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4.keys()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">dict_keys([3, 1, 4])<\/div>\n<h4>2. values() in dictionary<\/h4>\n<p>Likewise, the values() method returns a list of values in the dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4.values()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>dict_values([3, 1, 4])<\/p>\n<\/div>\n<h4>3. items() in dictionary<\/h4>\n<p>This method returns a list of key-value pairs.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4.items()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">dict_items([(3, 3), (1, 1), (4, 4)])<\/div>\n<h4>4. get() in dictionary<\/h4>\n<p>We first saw this function in section 4c. Now, let\u2019s dig a bit deeper.<\/p>\n<p>It takes one to two arguments. While the first is the key to search for, the second is the value to return if the key isn\u2019t found.<\/p>\n<p>The default value for this second argument is None.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4.get(3,0)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">3<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4.get(5,0)<\/pre>\n<p>Since the key 5 wasn\u2019t in the dictionary, it returned 0, like we specified.<\/p>\n<p>Any doubt yet in Python Dictionary? Leave a comment.<\/p>\n<h4>5. clear() in dictionary<\/h4>\n<p>The clear function\u2019s purpose is obvious. It empties the\u00a0Python dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4.clear()\r\n&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{}<\/div>\n<p>Let\u2019s reassign it though for further examples.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4={3:3,1:1,4:4}<\/pre>\n<h4>6. copy() in dictionary<\/h4>\n<p>First, let\u2019s see what shallow and deep copies are. A shallow copy only copies contents, and the new construct points to the same memory location.<\/p>\n<p>But a deep copy copies contents, and the new construct points to a different location. The copy() method creates a shallow copy of the\u00a0Python\u00a0dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict=dict4.copy()\r\n&gt;&gt;&gt; newdict<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{3: 3, 1: 1, 4: 4}<\/div>\n<h4>7. pop() in dictionary<\/h4>\n<p>This method is used to remove and display an item from the dictionary. It takes one to two arguments. The first is the key to be deleted, while the second is the value that\u2019s returned if the key isn\u2019t found.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.pop(4)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">4<\/div>\n<p>Now, let\u2019s try deleting the pair 4:4.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.pop(5,-1)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">-1<\/div>\n<p>However, unlike the get() method, this has no default None value for the second parameter.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.pop(5)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#191&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>newdict.pop(5)<\/p>\n<p>KeyError: 5<\/p>\n<\/div>\n<p>As you can see, it raised a KeyError when it couldn\u2019t find the key.<\/p>\n<h4>8. popitem() in dictionary<\/h4>\n<p>Let\u2019s first reassign the\u00a0Python dictionary newdict.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict={3:3,1:1,4:4,7:7,9:9}<\/pre>\n<p>Now, we\u2019ll try calling popitem() on this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.popitem()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">(9, 9)<\/div>\n<p>It popped the pair 9:9.<\/p>\n<p>Let\u2019s restart the shell and reassign the dictionary again and see which pair is popped.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">=============================== RESTART: Shell ===============================\r\n&gt;&gt;&gt; newdict={3:3,1:1,4:4,7:7,9:9}\r\n&gt;&gt;&gt; newdict.popitem()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">(9, 9)<\/div>\n<p>As you can see, the same pair was popped. We can interpret from this that the internal logic of the popitem() method is such that for a particular dictionary, it always pops pairs in the same order.<\/p>\n<h4>9. fromkeys() in dictionary<\/h4>\n<p>This method creates a new\u00a0Python dictionary from an existing one. To take an example, we try to create a new dictionary from newdict.<\/p>\n<p>While the first argument takes a set of keys from the dictionary, the second takes a value to assign to all those keys. But the second argument is optional.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.fromkeys({1,2,3,4,7},0)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}<\/div>\n<p>However, the keys don\u2019t have to be in a set.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.fromkeys((1,2,3,4,7),0)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}<\/div>\n<p>Like we\u2019ve seen so far, the default value for the second argument is None.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; newdict.fromkeys({'1','2','3','4','7'})<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{&#8216;4&#8217;: None, &#8216;7&#8217;: None, &#8216;3&#8217;: None, &#8216;1&#8217;: None, &#8216;2&#8217;: None}<\/div>\n<h4>10. update() in dictionary<\/h4>\n<p>The update() method takes another dictionary as an argument. Then it updates the dictionary to hold values from the other dictionary that it doesn\u2019t already.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict1={1:1,2:2}\r\n&gt;&gt;&gt; dict2={2:2,3:3}\r\n&gt;&gt;&gt; dict1.update(dict2)\r\n&gt;&gt;&gt; dict1<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 1, 2: 2, 3: 3}<\/div>\n<h3>Python Dictionary Operations<\/h3>\n<p>We learned about different classes of operators in Python earlier. Let\u2019s now see the applications.<\/p>\n<h4>1. Membership operation<\/h4>\n<p>We can apply the \u2018in\u2019 and \u2018not in\u2019 operators on a\u00a0Python dictionary to check whether it contains a certain key.<\/p>\n<p>For this example, we\u2019ll work on dict1.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict1<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 1, 2: 2, 3: 3}<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; 2 in dict1<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">True<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; 4 in dict1<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">False<\/div>\n<p>2 is a key in dict1, but 4 isn\u2019t. Hence, it returns True and False for them, correspondingly.<\/p>\n<h3>Python Iterate Dictionary<\/h3>\n<p>When in a for loop, you can also iterate on a Python dictionary like on a list, tuple, or set.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict4<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 1, 3: 3, 4: 4}<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; for i in dict4:\r\n\tprint(dict4[i]*2)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">2<br \/>\n6<br \/>\n8<\/div>\n<p>The above code, for every key in the\u00a0Python dictionary, multiplies its value by 2, and then prints it.<\/p>\n<h3>Nested Dictionary<\/h3>\n<p>Finally, let&#8217;s look at nested dictionaries. You can also place a Python dictionary as a value within a dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict1={4:{1:2,2:4},8:16}\r\n&gt;&gt;&gt; dict1<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{4: {1: 2, 2: 4}, 8: 16}<\/div>\n<p>To get the value for the key 4, write the following code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict1[4]<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">{1: 2, 2: 4}<\/div>\n<p>However, you can\u2019t place it as a key, because that throws an error.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; dict1={{1:2,2:4}:8,8:16}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#227&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>dict1={{1:2,2:4}:8,8:16}<\/p>\n<p>TypeError: unhashable type: &#8216;dict&#8217;<\/p>\n<\/div>\n<h3>Python Interview Questions on Dictionaries<\/h3>\n<p>1. What are Python dictionaries?<\/p>\n<p>2. How do you call a dictionary in Python?<\/p>\n<p>3. Explain how dictionaries work in Python?<\/p>\n<p>4. How do you read a dictionary in Python?<\/p>\n<p>5. How do you create an empty dictionary?<\/p>\n<h3>Conclusion<\/h3>\n<p>A Python dictionary works like a phone book, where each unique key points to a single value. Keys can be strings, numbers, or any immutable object, while values may be of any type at all. Under the hood, a fast hashing table lets you fetch or update a value in nearly constant time, no matter how big the dict grows, making it the go-to choice for lookup tasks such as counting words, storing config settings, or caching web requests.<\/p>\n<p>Whenever you are handling a huge amount of data, dictionaries are an important tool that is used to keep everything organised.<\/p>\n<p>In short, a Python dictionary is a powerful tool that is used to make the code simple, making it faster and more flexible.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the last few lessons, we have learned about some Python constructs like lists and tuples. Today, we will have a word about Python dictionaries, which is another type of data structure in Python.&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":35784,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[3810,3811,10496,10497],"class_list":["post-5646","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-dictionaries-in-python","tag-dictionary-in-python","tag-python-dictionaries","tag-python-dictionary"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Dictionary with Methods, Functions and Dictionary Operations - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn How to Create Dictionary in Python, access, reassign and delete python dictionaries. Learn built-in functions, methods &amp; operations\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-dictionary\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Dictionary with Methods, Functions and Dictionary Operations - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn How to Create Dictionary in Python, access, reassign and delete python dictionaries. Learn built-in functions, methods &amp; operations\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-dictionary\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-01-03T06:03:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-04-21T08:46:58+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Python-Dictionaries-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Dictionary with Methods, Functions and Dictionary Operations - DataFlair","description":"Learn How to Create Dictionary in Python, access, reassign and delete python dictionaries. Learn built-in functions, methods & operations","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-dictionary\/","og_locale":"en_US","og_type":"article","og_title":"Python Dictionary with Methods, Functions and Dictionary Operations - DataFlair","og_description":"Learn How to Create Dictionary in Python, access, reassign and delete python dictionaries. Learn built-in functions, methods & operations","og_url":"https:\/\/data-flair.training\/blogs\/python-dictionary\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-01-03T06:03:30+00:00","article_modified_time":"2026-04-21T08:46:58+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Python-Dictionaries-1.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Python Dictionary with Methods, Functions and Dictionary Operations","datePublished":"2018-01-03T06:03:30+00:00","dateModified":"2026-04-21T08:46:58+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/"},"wordCount":2110,"commentCount":3,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Python-Dictionaries-1.jpg","keywords":["dictionaries in python","dictionary in python","python dictionaries","python dictionary"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-dictionary\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/","url":"https:\/\/data-flair.training\/blogs\/python-dictionary\/","name":"Python Dictionary with Methods, Functions and Dictionary Operations - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Python-Dictionaries-1.jpg","datePublished":"2018-01-03T06:03:30+00:00","dateModified":"2026-04-21T08:46:58+00:00","description":"Learn How to Create Dictionary in Python, access, reassign and delete python dictionaries. Learn built-in functions, methods & operations","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-dictionary\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Python-Dictionaries-1.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Python-Dictionaries-1.jpg","width":1200,"height":628,"caption":"Python Dictionary"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-dictionary\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python Dictionary with Methods, Functions and Dictionary Operations"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/5646","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=5646"}],"version-history":[{"count":22,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/5646\/revisions"}],"predecessor-version":[{"id":147742,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/5646\/revisions\/147742"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/35784"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=5646"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=5646"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=5646"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}