{"componentChunkName":"component---src-templates-blog-post-js","path":"/blog/2021/08/stop-accessing-dictionary-items-by-index/","result":{"data":{"post":{"id":"-aa206024-4235-5990-a879-5e8944350dfc","publishedAt":"2021-08-23T15:54:00.000Z","_updatedAt":"2021-09-12T12:07:47Z","_rawExcerpt":[{"_key":"f725e7dc8733","_type":"block","children":[{"_key":"9de932f4c4a7","_type":"span","marks":[],"text":"Best practice on how to access dictionary items in Python"}],"markDefs":[],"style":"normal"}],"excerpt":[{"children":[{"text":"Best practice on how to access dictionary items in Python"}]}],"categories":[{"_id":"f6493711-d7ea-47c1-8355-6003f0845b51","title":"Python"}],"mainImage":{"crop":null,"hotspot":null,"asset":{"_id":"image-1826093704af806b5b28a4e5f98cfd5229112140-3300x2203-jpg","url":"https://cdn.sanity.io/images/ct7zmrwj/production/1826093704af806b5b28a4e5f98cfd5229112140-3300x2203.jpg"},"alt":null,"_rawCaption":[{"_key":"0c1440162079","_type":"block","children":[{"_key":"66e92a1a9888","_type":"span","marks":[],"text":"by "},{"_key":"5ccedd614933","_type":"span","marks":["fb14f4f2c9d1"],"text":"Chris Ried"}],"markDefs":[{"_key":"fb14f4f2c9d1","_type":"link","href":"https://unsplash.com/photos/ieic5Tq8YMk?utm_source=63921&utm_medium=referral"}],"style":"normal"}]},"title":"Stop Accessing dictionary items by index","slug":{"current":"stop-accessing-dictionary-items-by-index"},"_rawBody":[{"_key":"b04233b6a50f","_type":"block","children":[{"_key":"f02730102c3d","_type":"span","marks":[],"text":"The problem "}],"markDefs":[],"style":"h2"},{"_key":"5b406afab556","_type":"block","children":[{"_key":"7b502d0e0eb2","_type":"span","marks":[],"text":"Since most of us are lazy programmers, it's more convenient to access items from a Python dictionary by index like this: "},{"_key":"426a32df8904","_type":"span","marks":["code"],"text":"my_dict["},{"_key":"a87166367c57","_type":"span","marks":["em","code"],"text":"key"},{"_key":"8e3f21ad1123","_type":"span","marks":["code"],"text":"]."}],"markDefs":[],"style":"normal"},{"_key":"632dd9345263","_type":"block","children":[{"_key":"84e3011f8627","_type":"span","marks":[],"text":"Warning: Accessing items from a dictionary by index could return a "},{"_key":"1dd143081349","_type":"span","marks":["code"],"text":"KeyError"},{"_key":"d8ad5951bdee","_type":"span","marks":[],"text":" exception if the key is missing and will break the flow of your application."}],"markDefs":[],"style":"blockquote"},{"_key":"81491875436c","_type":"block","children":[{"_key":"32612d505cda","_type":"span","marks":[],"text":"Even though this might seem small and irrelevant, it's really annoying when it happens, especially if you have a big and complex application, since this method will break the flow."}],"markDefs":[],"style":"normal"},{"_key":"1326cae701f2","_type":"code","code":"Traceback (most recent call last): File \"<input>\", line 1, in <module> KeyError: '<KEY_NAME>'","language":"python"},{"_key":"6ca0cc363aeb","_type":"block","children":[{"_key":"691a15b5939d","_type":"span","marks":[],"text":"Workarounds"}],"markDefs":[],"style":"h2"},{"_key":"88acaf2c1937","_type":"block","children":[{"_key":"4ba660e27bed","_type":"span","marks":[],"text":"One might argue you can wrap a piece of code with the "},{"_key":"4fbf4e4df6fa","_type":"span","marks":["code"],"text":"try"},{"_key":"eaa7cef0efe1","_type":"span","marks":[],"text":" statement, or use "},{"_key":"2cd7e9afdfe0","_type":"span","marks":["code"],"text":"top-level error handlers"},{"_key":"5208220efd5e","_type":"span","marks":[],"text":" on your service, but why do this when you can prevent all of this overhead by using a build-in method instead?"}],"markDefs":[],"style":"normal"},{"_key":"980b25b77b3f","_type":"block","children":[{"_key":"b8ca1d71d8de","_type":"span","marks":[],"text":"Best Practice"}],"markDefs":[],"style":"h2"},{"_key":"07cec44e738c","_type":"block","children":[{"_key":"a245d234f6a3","_type":"span","marks":[],"text":"Best Practise: "},{"_key":"6fcf1f15b17c","_type":"span","marks":["code"],"text":""},{"_key":"637f9408583c","_type":"span","marks":["code"],"text":"get"},{"_key":"57398b1713a9","_type":"span","marks":["code"],"text":"("},{"_key":"11f2806caa45","_type":"span","marks":["code"],"text":"key"},{"_key":"74181c5a5735","_type":"span","marks":["code"],"text":"[, "},{"_key":"037fdd4802ce","_type":"span","marks":["code"],"text":"default"},{"_key":"51037380e912","_type":"span","marks":["code"],"text":"])"},{"_key":"06254d08995f","_type":"span","marks":[],"text":""},{"_key":"ba318859310d","_type":"span","marks":[],"text":""}],"markDefs":[{"_key":"99c1e8aa40f6","_type":"link","href":"https://docs.python.org/3/library/exceptions.html#KeyError"}],"style":"blockquote"},{"_key":"165e900509bb","_type":"block","children":[{"_key":"053ddd0bb79712","_type":"span","marks":[],"text":"From the "},{"_key":"a0f2aa334391","_type":"span","marks":["fdc7fd7f44a1"],"text":"Python Official Documentation"},{"_key":"334cb13ca3b5","_type":"span","marks":[],"text":""}],"markDefs":[{"_key":"fdc7fd7f44a1","_type":"link","href":"https://docs.python.org/3/library/stdtypes.html#:~:text=get(key%5B%2C%20default,raises%20a%20KeyError."}],"style":"normal"},{"_key":"63c2ef3b8d7d","_type":"block","children":[{"_key":"eb7da24bc5bb","_type":"span","marks":[],"text":""},{"_key":"097e40930682","_type":"span","marks":[],"text":"Return the value for "},{"_key":"36e5d2c8f7b5","_type":"span","marks":["em"],"text":"key"},{"_key":"9d81edc311c9","_type":"span","marks":[],"text":" if "},{"_key":"4c8e2f684ee7","_type":"span","marks":["em"],"text":"key"},{"_key":"665acd009ed1","_type":"span","marks":[],"text":" is in the dictionary, else "},{"_key":"a8bd91ed6c61","_type":"span","marks":["em"],"text":"default"},{"_key":"cbed05cb53d3","_type":"span","marks":[],"text":". If "},{"_key":"8493f6a0b462","_type":"span","marks":["em"],"text":"default"},{"_key":"8cdfc32bd8d8","_type":"span","marks":[],"text":" is not given, it defaults to "},{"_key":"e23debcc3476","_type":"span","marks":["code"],"text":"None"},{"_key":"16c37a5887af","_type":"span","marks":[],"text":", so that this method never raises a "},{"_key":"aa8fb7f322c9","_type":"span","marks":["code","b34cb36eea2a"],"text":"KeyError"},{"_key":"9039892a5ce0","_type":"span","marks":[],"text":"."}],"markDefs":[{"_key":"b34cb36eea2a","_type":"link","href":"https://docs.python.org/3/library/exceptions.html#KeyError"}],"style":"blockquote"},{"_key":"90be29b7ebe9","_type":"block","children":[{"_key":"5b93b893f2e7","_type":"span","marks":[],"text":"This is the safest choice since the "},{"_key":"1320535bcb80","_type":"span","marks":["code"],"text":".get()"},{"_key":"f066e920f665","_type":"span","marks":[],"text":" method will return "},{"_key":"4997f6f99c7a","_type":"span","marks":["code"],"text":"None"},{"_key":"5617f88353f0","_type":"span","marks":[],"text":" if the key is not in the dictionary. But again, be careful, you should always design your system to handle the "},{"_key":"db5ed4d24291","_type":"span","marks":["code"],"text":"None"},{"_key":"d0e28efb7c42","_type":"span","marks":[],"text":" scenarios as well."}],"markDefs":[],"style":"normal"},{"_key":"f5fdfdccb960","_type":"block","children":[{"_key":"76515b5a1f1e","_type":"span","marks":[],"text":"Using this method you have more flexibility as to what to return if the key is missing. By default, this method will return None. You could also specify a different default value or even a callback. "}],"markDefs":[],"style":"normal"},{"_key":"e1fa721ee1c5","_type":"code","code":"d = {'key1': 1, 'key2': 2}\n# Returns None\nd.get('new')\n\n# Returns 6\nsome_number = 6\nd.get('new', some_number)\n\ndef callback():\n    return 2\n\n# Returns the function output\nd.get('new', callback())","language":"python"},{"_key":"f0617435695e","_type":"block","children":[{"_key":"c17a04c244de","_type":"span","marks":[],"text":"Create your custom Dictionary"}],"markDefs":[],"style":"h2"},{"_key":"786afb051c8d","_type":"block","children":[{"_key":"d59a83cc82e8","_type":"span","marks":[],"text":"Well, if you are still stubborn and still want to access your items by index, there is still a way. You can create your own version of the dictionary. You can create a new class that inherits the "},{"_key":"37f95698761a","_type":"span","marks":["code"],"text":"dict"},{"_key":"aa5447ce5069","_type":"span","marks":[],"text":" and implement the "},{"_key":"a90e7a1e21f1","_type":"span","marks":["code"],"text":"__missing__"},{"_key":"4f57c8032a46","_type":"span","marks":[],"text":" function in order to return something when the key is not found. "}],"markDefs":[],"style":"normal"},{"_key":"e8c94f1aa319","_type":"block","children":[{"_key":"879a24526d1f","_type":"span","marks":[],"text":"If you decide to mimic the same functionality as the "},{"_key":"fdacd925eebf","_type":"span","marks":["code"],"text":"get(key)"},{"_key":"f701d9bb7e81","_type":"span","marks":[],"text":" method, you can use the example below:"}],"markDefs":[],"style":"normal"},{"_key":"d8b2b0f56dad","_type":"code","code":"class CustomDict(dict):\n    def __missing__(self, key):\n        return None","language":"python"},{"_key":"9839df5a91fe","_type":"block","children":[{"_key":"5df412712291","_type":"span","marks":[],"text":"By doing so, you ensure that if the key does not exist, the method will return None instead of raising a KeyError exception. You can also be creative and do something that fits your own requirements. If you decide to return the max value you currently have in your dictionary you can do the following:"}],"markDefs":[],"style":"normal"},{"_key":"de3dd99759f2","_type":"code","code":"class CustomDict(dict):\n    def __missing__(self, key):\n        return max(self.values())\n\nd = CustomDict()\nd.update({\n    'key1':1,\n    'key2':2\n})\n# Will print 2\nprint(d['new_key'])","language":"python"},{"_key":"f51a69591128","_type":"block","children":[{"_key":"726dfa36502f","_type":"span","marks":[],"text":""}],"markDefs":[],"style":"normal"}],"authors":[{"_key":"420c1fc060a7","person":{"name":"Leonidas  Constantinou","twitter":"leonidas_con","devto":null,"image":{"crop":null,"hotspot":null,"asset":{"_id":"image-f88a6f65a5db9cea1c5284e8f8ba8988c6ae91b9-966x1128-jpg","url":"https://cdn.sanity.io/images/ct7zmrwj/production/f88a6f65a5db9cea1c5284e8f8ba8988c6ae91b9-966x1128.jpg"}}},"roles":["illustration","text","editor"]}]}},"pageContext":{"id":"-aa206024-4235-5990-a879-5e8944350dfc"}},"staticQueryHashes":["161526108","2049262650","3344910397","3527466637"]}