{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Dario Radečić",
  "title_listed": "Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries",
  "keywords": "Python,字典",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/nested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f/",
  "publish_date": "2023-04",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "bba80bdd6168",
  "collected_at": "2026-10-01T21:23:01",
  "title": "Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries\nHow to work with Nested Dictionary in Python? This article teaches you everything you need to know about Python Nested Dictionaries.\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nApril 18, 202313 min read\n![Photo by Kelly Sikkema on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0WrDTY9iMfUWfmb2R-scaled.jpg)\nPhoto by [Kelly Sikkema](https://unsplash.com/@kellysikkema?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\n## What is Nested Dictionary in Python?\nOne common data structure in Python is a nested dictionary, or a dictionary that can have other dictionaries as values for a given key. Beginners hate nested dictionaries because they require more time to work with and parse correctly, but it's nothing you can't manage with a bit of practice.\n> [_New to Python? Learn basic Dictionaries First._](https://betterdatascience.com/python-dictionaries/)\nToday you'll learn what is a nested dictionary, why to use nested dictionaries in Python, how to loop through a nested dictionary in Python, and much more. Regarding library imports, stick this to the top of your script or notebook:\npython\n\n```\nimport pprint\npp = pprint.PrettyPrinter(depth=4)\n```\n\nIt will take care of formatting when printing nested dictionaries, so they're a bit easier to read.\n* * *\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Computer Science](https://roadmap.sh/computer-science) roadmaps.\n## How to Create a Nested Dictionary in Python\nThere are many ways to create a nested dictionary, but you'll primarily use two if you're creating them from scratch in Python.\n### Using Regular Python Notation\nThe first way to create a nested Python dictionary is by leveraging regular Python notation. It means you don't have to use any specific functions or libraries to create a dictionary. Simply assign it to a variable name, and format the entire thing as JSON.\nHere's an example - the following code snippet creates a nested dictionary of employees, where employee email is set for the dictionary key, and additional information as a dictionary value. As you can see, the dictionary value is also a dictionary:\npython\n\n```\nemployees = {\n    \"bdoe@email.com\": {\n        \"first_name\": \"Bob\", \n        \"last_name\": \"Doe\",\n        \"address\": {\n            \"city\": \"New York\",\n            \"street\": \"1st Street\",\n            \"house_number\": 1\n        }\n    },\n    \"mmarkson@email.com\": {\n        \"first_name\": \"Mark\", \n        \"last_name\": \"Markson\",\n        \"address\": {\n            \"city\": \"San Diego\",\n            \"street\": \"2nd Street\",\n            \"house_number\": 2\n        }\n    }\n}\n\npp.pprint(employees)\n```\n\nHere's what this nested dictionary looks like:\n![Image 1 - Nested dictionary of employees \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1gtv8OSh_7HOYevfSkG1zdQ.png)\n_Image 1 - Nested dictionary of employees (image by author)_\nOverall, we have a dictionary with two keys (emails). Each of those keys has a dictionary for a value, and there's even a third dictionary assigned to the `address` key.\n**Dictionaries aren't ordered** , so that's why you're seeing the data not reflecting the ordering specified in the code. Don't worry about that.\n### Using the zip() Function\nAn alternative way to create a nested dictionary in Python is by using the `zip()` function. It's used to iterate over two or more iterators at the same time.\nTo demonstrate, we'll declare two lists:\n  * `employee_emails` - A list of emails that will represent the dictionary keys\n  * `employee_details` - A list of details for each employee, such as first name, last name, and address.\n\n\nIf you declare your data in this way, you can pass both to `zip()` and wrap everything inside a call to `dict()`. This will assign appropriate key-value pairs. Here's the code:\npython\n\n```\nemployee_emails = [\"bdoe@email.com\", \"mmarkson@email.com\"]\n\nemployee_details = [\n    {\n        \"first_name\": \"Bob\", \n        \"last_name\": \"Doe\", \n        \"address\": {\n            \"city\": \"New York\", \n            \"street\": \"1st Street\", \n            \"house_number\": 1\n        }\n    },\n    {\n        \"first_name\": \"Mark\", \n        \"last_name\": \"Markson\", \n        \"address\": {\n            \"city\": \"San Diego\", \n            \"street\": \"2nd Street\", \n            \"house_number\": 2\n        }\n    }\n]\n\nemployees = dict(zip(employee_emails, employee_details))\npp.pprint(employees)\n```\n\nThe resulting data looks the same as what we had before:\n![Image 2 - Nested dictionary of employees \\(2\\) \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1gtv8OSh_7HOYevfSkG1zdQ.png)\n_Image 2 - Nested dictionary of employees (2) (image by author)_\nIn practice, there's no reason to use this approach to declare nested dictionaries. It's messy and takes longer to write. Just stick to the first one and you'll be good to go.\nUp next, let's see how to access elements of a nested dictionary in Python.\n## How to Access Elements of a Nested Dictionary\nYou can access elements of a nested dictionary just like you would for a normal one, with one exception - **you now need to add an additional set(s) of brackets.**\nHere are a couple of examples of what you can do:\n  * Access a single element\n  * Access a single element which is also a dictionary\n  * Concatenate multiple nested dictionary values\n\n\nOr in code:\npython\n\n```\n# Access element that contains a string\nprint(employees[\"bdoe@email.com\"][\"first_name\"])\n\n# Access element that contains a string\nprint(employees[\"bdoe@email.com\"][\"last_name\"])\n\n# Access element that contains a dictionary\nprint(employees[\"bdoe@email.com\"][\"address\"])\n\n# Combine multiple elements\nprint(f\"{employees['bdoe@email.com']['first_name']} {employees['bdoe@email.com']['last_name']} from {employees['bdoe@email.com']['address']['city']}\")\n```\n\nHere's the output you should see:\n![Image 3 - Accessing elements of a nested Python dictionary \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1hFy1cwTlij9CfjSVzCRkuw.png)\n_Image 3 - Accessing elements of a nested Python dictionary (image by author)_\nOverall, you need as many brackets as there are levels in a nested dictionary if you want to get to the bottom. For example, to get the city for `bdoe@email.com`, you would write `employees[\"bdoe@email.com\"][\"address\"][\"email\"]`. Easy!\n## How to Change Values in a Nested Dictionary\nYou now know how to access elements of a nested dictionary, but how can you change the values? It's quite easy, and you can either change the values one by one or tackle multiple values at once.\n### Change a Single Value in a Nested Dictionary\nYou can change a single value in a nested dictionary by accessing it and assigning a new value.\nThe following example shows you how to change the complete `address` for one employee, one value at a time:\npython\n\n```\n# Change values one by one\nemployees[\"bdoe@email.com\"][\"address\"][\"city\"] = \"San Francisco\"\nemployees[\"bdoe@email.com\"][\"address\"][\"street\"] = \"5th Street\"\nemployees[\"bdoe@email.com\"][\"address\"][\"house_number\"] = 5\n\npp.pprint(employees[\"bdoe@email.com\"])\n```\n\nThe updated employee now looks like this:\n![Image 4 - Changing a single value in a nested dictionary \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1Q6HGt_9XMNYBcAk7GNuT4A.png)\n_Image 4 - Changing a single value in a nested dictionary (image by author)_\nThat's great, but can you change the `address` in one line? Sure you can, let's explore how next.\n### Change Multiple Values in a Nested Dictionary\nThe `address` property is a dictionary itself, which means you can change it completely in one line of Python code:\npython\n\n```\n# Change multiple values at once\nemployees[\"mmarkson@email.com\"][\"address\"] = {\"city\": \"Los Angeles\", \"street\": \"15th Street\", \"house_number\": 15}\n\npp.pprint(employees[\"mmarkson@email.com\"])\n```\n\nHere's what the updated employee looks like:\n![Image 5 - Changing multiple values in a nested dictionary \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1Mecb7s5V-g8hR3F9opI7nw.png)\n_Image 5 - Changing multiple values in a nested dictionary (image by author)_\nYou now know how to access and change nested dictionary elements, so next we'll go over adding new elements to a nested dictionary in Python.\n## How to Add Elements to a Nested Dictionary\nAdding new elements to a nested dictionary in Python boils down to assigning a new key-value pair. It's that simple!\nThe code snippet below declares two variables to hold the key and value for the new nested dictionary item, and then adds this pair by using the `dictionary[key] = value` assignment operator:\npython\n\n```\nnew_employee_email = \"jswift@email.com\"\nnew_employee_details = {\n    \"first_name\": \"Jane\", \n    \"last_name\": \"Swift\", \n    \"address\": {\n        \"city\": \"Boston\", \n        \"street\": \"10th Street\", \n        \"house_number\": 10\n    }\n}\n\n# dictionary[key] = value\nemployees[new_employee_email] = new_employee_details\n\npp.pprint(employees)\n```\n\nOur updated nested dictionary now has 3 records:\n![Image 6 - Adding elements to a nested dictionary in Python \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/15Y5pGloUDwYZNvpEoN1hRQ.png)\n_Image 6 - Adding elements to a nested dictionary in Python (image by author)_\nThat's addition, so next let's go over deletion.\n## How to Delete Elements from a Nested Dictionary\nYou can use Python's `del` keyword followed by the name of the dictionary and a key you want to delete. For example, run `del d[\"name\"]` to delete the key-value pair under the key of `name` in the dictionary `d`.\nIn our example, let's use `del` to delete the newly added employee:\npython\n\n```\ndel employees[\"jswift@email.com\"]\n\npp.pprint(employees)\n```\n\nAnd we're back to only two records now:\n![Image 7 - Deleting elements from a nested dictionary \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1TntgZAMCEuFiXcy9uPLXkw.png)\n_Image 7 - Deleting elements from a nested dictionary (image by author)_\nUp next, let's go over merging two or more dictionaries.\n## How to Merge Two Nested Dictionaries\nDictionary merging just means you want to take two or more dictionaries and combine them into a single one. It helps if the structure of dictionaries is identical, but it's not required, since this is Python.\nTo demonstrate, let's declare a new nested dictionary of employees:\npython\n\n```\nnew_employees = {\n    \"jswift@email.com\": {\n        \"first_name\": \"Jane\", \n        \"last_name\": \"Swift\",\n        \"address\": {\n            \"city\": \"Boston\",\n            \"street\": \"25th Street\",\n            \"house_number\": 25\n        }\n    },\n    \"pjohnson@email.com\": {\n        \"first_name\": \"Patrick\", \n        \"last_name\": \"Johnson\",\n        \"address\": {\n            \"city\": \"Miami\",\n            \"street\": \"50th Street\",\n            \"house_number\": 50\n        }\n    }\n}\n\npp.pprint(new_employees)\n```\n\nHere's what it looks like:\n![Image 8 - Two new employees \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1nKjWwmaAQkDZfVnUk1Dz6g.png)\n_Image 8 - Two new employees (image by author)_\nThe idea is to add this dictionary to the one we already have, and there are two ways to do so.\n### Merge Two Dictionaries with the update() Function\nThe `update()` function _updates_ one dictionary with the contents of another. The updating happens inplace, which means you don't have to reassign the variable.\nHere's an example:\npython\n\n```\nemployees.update(new_employees)\n\npp.pprint(employees)\n```\n\nOur updated nested dictionary now has four records:\n![Image 9 - Merging nested dictionaries \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1uvWKC8fF51UTziOOjEJDQw.png)\n_Image 9 - Merging nested dictionaries (image by author)_\nThis function is easy to work with, but the downside is that **you can only add one dictionary at a time**. The next approach is a bit more flexible.\n### Merge Two Dictionaries with **kwargs\nThe `**kwargs` approach might look strange to newcomers, but it essentially just unpacks a dictionary. By doing so, you can unpack as many dictionaries as you want into a single new dictionary.\nHere's an example:\npython\n\n```\nemps_merged = {**employees, **new_employees}\n\npp.pprint(emps_merged)\n```\n\nThe merged nested dictionary is identical to the one we had earlier:\n![Image 10 - Merging nested dictionaries \\(2\\) \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1uvWKC8fF51UTziOOjEJDQw.png)\n_Image 10 - Merging nested dictionaries (2) (image by author)_\nUltimately, it's up to you to decide on the best merging approach. We recommend `**kwargs` since you can merge dozens of dictionaries in a single line of Python code.\n## How to Iterate Through a Nested Dictionary\nThere's no one-size-fits-all solution when it comes to iterating through a nested dictionary in Python. A structure of a dictionary item will vary, which means you'll have to customize the code every time.\nTo show you how, we'll go over two examples, one simpler and the other a bit heavier on the code side.\nThe first example iterates over all dictionary items and prints the key, and then also iterates through the corresponding value and prints it. Here's the code:\npython\n\n```\n# Keys and values\nfor emp_email, emp_info in employees.items():\n    print(f\"EMAIL: {emp_email}\")\n\n    # For each key that belongs to a dictionary at the given email\n    for key in emp_info:\n        # Print the corresponding key and value\n        print(f\"{key} = {emp_info[key]}\")\n\n    print()\n```\n\nThis is what you should see:\n![Image 11 - Iterating through a nested dictionary \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/17TO6BHeApFEr6FEtWsmnMg.png)\n_Image 11 - Iterating through a nested dictionary (image by author)_\nThis approach might work if you don't have an additional level of nesting, similar to what we have with `address`. It's much more challenging to _address_ this, but let's give it a try next.\n### More Advanced Iteration Example\nThe idea now is to step into the `address` dictionary and print all of the elements it contains.\nTo make the code a bit more robust, we'll check if the item is a dictionary, and if so, iterate through its items. If the tem is not a dictionary, we'll simply print it:\npython\n\n```\n# Keys and values\nfor emp_email, emp_info in employees.items():\n    print(f\"EMAIL: {emp_email}\")\n\n    # For every key in the inner dictionary\n    for key in emp_info:\n\n        # Check if a type is a dictionary\n        if type(emp_info[key]) is dict:\n            print(f\"{key}:\")\n\n            # Print nested items\n            for item in emp_info[key]:\n                print(f\"t{item} = {emp_info[key][item]}\")\n        # Not a dictionary, print the value\n        else:\n            print(f\"{key} = {emp_info[key]}\")\n\n    print()\n```\n\nHere's what you should see on the screen:\n![Image 12 - Iterating through a nested dictionary \\(2\\) \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1TrW_8P0vzIQI015rJAw8IQ.png)\n_Image 12 - Iterating through a nested dictionary (2) (image by author)_\nOverall, we've managed to parse our nested dictionary structure, but again, **this won't work on all nested dictionaries**. You'll have to customize the code snippet to accommodate your use case, which can be tricky and time-consuming.\n## How to Flatten a Nested Dictionary\nFlattening a nested dictionary means you want to get a dictionary that doesn't contain any dictionaries or lists inside.\nThis is a very common data preprocessing technique when parsing nested JSON documents to a Pandas DataFrame. If that's what you're dealing with, you know the structure of the input data will be quite different.\nMost of the time, you'll have a **list of dictionaries**. We'll declare one such list below, and add the `email` property inside each employee object instead of using it as a dictionary key:\npython\n\n```\nemployees = [\n    {\n        \"first_name\": \"Bob\", \n        \"last_name\": \"Doe\",\n        \"email\": \"bdoe@email.com\",\n        \"address\": {\n            \"city\": \"New York\",\n            \"street\": \"1st Street\",\n            \"house_number\": 1\n        }\n    },\n    {\n        \"first_name\": \"Mark\", \n        \"last_name\": \"Markson\",\n        \"email\": \"mmarkson@email.com\",\n        \"address\": {\n            \"city\": \"San Diego\",\n            \"street\": \"2nd Street\",\n            \"house_number\": 2\n        }\n    }\n]\n```\n\nOnce you have the data in this format, it's time to flatten it. The following recursive function flattens one record, or one dictionary element inside a list. For any nested dictionary, it finds it will flatten it in a way that the key renames to the full _path_.\nThe `flatten_dict()` function has to be applied on each record in a list of dictionaries, meaning you can use either a Python loop or a list comprehension.\nHere's an example:\npython\n\n```\ndef flatten_dict(d: dict) -> dict:\n    out = {}\n\n    def flatten(x, name: str = ''):\n        if type(x) is dict:\n            for a in x:\n                flatten(x[a], name + a + '_')\n        elif type(x) is list:\n            i = 0\n            for a in x:\n                flatten(a, name + str(i) + '_')\n                i += 1\n        else:\n            out[name[:-1]] = x\n    flatten(d)\n\n    return out\n\n# Apply the function to each row\nemployees_flat = [flatten_dict(emp) for emp in employees]\npp.pprint(employees_flat)\n```\n\nWe now have a completely flat structure:\n![Image 13 - Flattening a nested dictionary \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1WnzIw_UU5UbTyJVnG-aB3A.png)\n_Image 13 - Flattening a nested dictionary (image by author)_\nNote how `address` was appended before its inner key-value pairs, so we still get the idea of where it belonged originally.\nNow when you have a flat list of dictionaries, you can convert it into a Pandas DataFrame.\n## Nested Dictionary Python to Pandas DataFrame\nIf you want to convert a nested dictionary to a Pandas DataFrame, you'll have to flatten it first. Otherwise, you'll get weird indexing and possibly a dictionary for the value of a single cell.\nLet's demonstrate a bad practice first, so you can get the idea of why flatten the data. Below we have an identical dictionary of employees to the one we used throughout the article. We're then using it in a call to `pd.DataFrame()`:\npython\n\n```\nimport pandas as pd\n\nemployees = {\n    \"bdoe@email.com\": {\n        \"first_name\": \"Bob\", \n        \"last_name\": \"Doe\",\n        \"address\": {\n            \"city\": \"New York\",\n            \"street\": \"1st Street\",\n            \"house_number\": 1\n        }\n    },\n    \"mmarkson@email.com\": {\n        \"first_name\": \"Mark\", \n        \"last_name\": \"Markson\",\n        \"address\": {\n            \"city\": \"San Diego\",\n            \"street\": \"2nd Street\",\n            \"house_number\": 2\n        }\n    }\n}\n\npd.DataFrame(employees)\n```\n\nHere's what the resulting DataFrame looks like:\n![Image 14 - Nested dictionary to a Pandas DataFrame \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1VG0hMU8hIaXeYAxboG3CbA.png)\n_Image 14 - Nested dictionary to a Pandas DataFrame (image by author)_\nTerrible and not usable. **You need to pass a list of flattened dictionaries to**`**pd.DataFrame()**`to get back the data in the appropriate format.\nYou already know how to flatten a nested dictionary, so this should feel like a walk in the park:\npython\n\n```\nemployees = [\n    {\n        \"first_name\": \"Bob\", \n        \"last_name\": \"Doe\",\n        \"email\": \"bdoe@email.com\",\n        \"address\": {\n            \"city\": \"New York\",\n            \"street\": \"1st Street\",\n            \"house_number\": 1\n        }\n    },\n    {\n        \"first_name\": \"Mark\", \n        \"last_name\": \"Markson\",\n        \"email\": \"mmarkson@email.com\",\n        \"address\": {\n            \"city\": \"San Diego\",\n            \"street\": \"2nd Street\",\n            \"house_number\": 2\n        }\n    }\n]\n\n# Flatten the records first\nemployees_flat = [flatten_dict(emp) for emp in employees]\npd.DataFrame(employees_flat)\n```\n\nThe DataFrame is now much easier to understand and analyze:\n![Image 15 - Nested dictionary to a Pandas DataFrame \\(2\\) \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1FCVmeeZd9eImupV5yIDEwg.png)\n_Image 15 - Nested dictionary to a Pandas DataFrame (2) (image by author)_\nAnd finally, let's cover nested dictionary to JSON conversion.\n## Nested Dictionary Python to JSON File\nJSON and Python dictionaries go hand in hand, meaning you can easily go from a JSON file to a Python dictionary and vice-versa.\nWe'll show you how to go from a nested Python dictionary to a JSON file. You'll need to import the `json` module and pass in your dictionary to `json.dumps()`. The optional `indent` parameter controls the indentation of nested structures inside a dictionary.\nHere's the code:\npython\n\n```\nimport json\n\nemployees = {\n    \"bdoe@email.com\": {\n        \"first_name\": \"Bob\", \n        \"last_name\": \"Doe\",\n        \"address\": {\n            \"city\": \"New York\",\n            \"street\": \"1st Street\",\n            \"house_number\": 1\n        }\n    },\n    \"mmarkson@email.com\": {\n        \"first_name\": \"Mark\", \n        \"last_name\": \"Markson\",\n        \"address\": {\n            \"city\": \"San Diego\",\n            \"street\": \"2nd Street\",\n            \"house_number\": 2\n        }\n    }\n}\n\njson_object = json.dumps(employees, indent=4) \nprint(json_object)\n```\n\nAnd this is what your JSON object should look like:\n![Image 16 - Nested dictionary to a JSON object \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1HyJ_8B3caH3tMhx8n1Qc-w.png)\n_Image 16 - Nested dictionary to a JSON object (image by author)_\nYou can now use Python's context manager syntax to write the JSON object to a file. This code snippet writes it to a file named `employees.json`:\npython\n\n```\nwith open(\"employees.json\", \"w\") as f:\n    json.dump(employees, f)\n```\n\nYou can open the JSON file in any text editor or even in JupyterLab. You'll see something similar to this:\n![Image 17 - Nested dictionary to a JSON file \\(image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1V1J0u6hOYqAXrABXZzOGHw.png)\n_Image 17 - Nested dictionary to a JSON file (image by author)_\nAnd that's how you can work with nested dictionaries in Python. Let's make a short recap next.\n* * *\n## Summing up Nested Dictionary Python\nThere's a lot that goes into working with nested dictionaries in Python. You can access individual values, change them, add new rows, delete old ones, merge multiple dictionaries, iterate over them, and even convert the entire thing to a Pandas DataFrame or JSON file.\nUnfortunately, there's no one-size-fits-all solution when it comes to nested dictionaries. The structure of one will vary from project to project, which means you'll have to customize the code to match your scenario. That's especially true when it comes to iterating through nested dictionaries.\nThis article should give you a good starting point and will cover 95% of scenarios, and you can always explore further on your own.\n_What's your favorite thing about nested dictionaries? Are they giving you a lot of headaches in daily data science tasks?_ Let me know in the comment section below.\n* * *\n_Loved the article? Become a_[ _Medium member_](https://medium.com/@radecicdario/membership) _to continue learning without limits. I'll receive a portion of your membership fee if you use the following link, with no extra cost to you._\n> [**Join Medium with my referral link - Dario Radečić**](https://medium.com/@radecicdario/membership)\n* * *\n_Originally published at_[ _https://betterdatascience.com_](https://betterdatascience.com/nested-dictionary-python/) _on April 18, 2023._\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657095692_93hujy.png)\nWritten By\n## [Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nhttps://writingfordevs.substack.com\n[See all from Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\n[Coding](https://towardsdatascience.com/tag/coding/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Programming](https://towardsdatascience.com/tag/programming/)[Python](https://towardsdatascience.com/tag/python/)[Towards Data Science](https://towardsdatascience.com/tag/towards-data-science/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fnested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f%2F&title=Nested%20Dictionary%20Python%20-%20A%20Complete%20Guide%20to%20Python%20Nested%20Dictionaries)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fnested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f%2F&title=Nested%20Dictionary%20Python%20-%20A%20Complete%20Guide%20to%20Python%20Nested%20Dictionaries)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fnested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f%2F&text=Nested%20Dictionary%20Python%20-%20A%20Complete%20Guide%20to%20Python%20Nested%20Dictionaries)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/01/0IbRY6w6uR9jRQwCn-scaled.jpg)](https://towardsdatascience.com/top-3-methods-for-handling-skewed-data-1334e0debf45/)\n## [Top 3 Methods for Handling Skewed Data](https://towardsdatascience.com/top-3-methods-for-handling-skewed-data-1334e0debf45/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIs skewed data messing up the power of your predictive model? Let's find out\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nJanuary 4, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/06/svd_with_4_vectors.gif)](https://towardsdatascience.com/animating-linear-transformations-with-quiver/)\n## [Animating Linear Transformations with Quiver](https://towardsdatascience.com/animating-linear-transformations-with-quiver/)\n[Data Visualization](https://towardsdatascience.com/category/data-science/data-visualization/)\nA useful tool in your quiver\n[Artemij Lehmann](https://towardsdatascience.com/author/artemij.lehmann/)\nJune 18, 20258 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0BVBq7eNCvhBJnc_i-scaled.jpg)](https://towardsdatascience.com/practical-guide-to-entity-resolution-part-3-1b2c262f50a7/)\n## [Practical Guide to Entity Resolution - part 3](https://towardsdatascience.com/practical-guide-to-entity-resolution-part-3-1b2c262f50a7/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nFeaturization and blocking key generation\n[Yifei Huang](https://towardsdatascience.com/author/yifei-huang/)\nNovember 3, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/18mwg2tMRuSzs20gCox9aQA.jpeg)](https://towardsdatascience.com/is-kubernetes-on-premise-viable-8b488368af56/)\n## [Is Kubernetes on Premise viable?](https://towardsdatascience.com/is-kubernetes-on-premise-viable-8b488368af56/)\n[Programming](https://towardsdatascience.com/category/programming/)\nThe cloud is the best solution, but what if is not available?\n[Daniele Fontani](https://towardsdatascience.com/author/daniele-fontani/)\nMay 11, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/04/0_WT4QQ7xSn5fYRUn-scaled.jpg)](https://towardsdatascience.com/your-first-neural-network-in-pytorch-725631ae0fc/)\n## [Your First Neural Network in PyTorch](https://towardsdatascience.com/your-first-neural-network-in-pytorch-725631ae0fc/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLet's get that PC warm.\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nApril 17, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0DSfW3MBnqq9JnYtk-scaled.jpg)](https://towardsdatascience.com/open-source-models-temperature-scaling-re-ranking-and-more-dont-miss-our-latest-llm-must-reads-ed8e43190333/)\n## [Open-Source Models, Temperature Scaling, Re-Ranking, and More: Don't Miss Our Latest LLM Must-Reads](https://towardsdatascience.com/open-source-models-temperature-scaling-re-ranking-and-more-dont-miss-our-latest-llm-must-reads-ed8e43190333/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nOur weekly selection of must-read Editors' Picks and original features\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nMay 16, 20244 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0Oq_OdOVeEcDLA98V.jpg)](https://towardsdatascience.com/common-causes-of-data-leakage-and-how-to-spot-them-17113406f9f8/)\n## [Common Causes of Data Leakage and how to Spot Them](https://towardsdatascience.com/common-causes-of-data-leakage-and-how-to-spot-them-17113406f9f8/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLet's learn how to identify and deal with the common causes of data leakage in ML models\n[Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\nMay 17, 20248 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/09/0udXy6a2qaip0CS9q-scaled.jpg)](https://towardsdatascience.com/a-data-scientists-guide-to-stakeholders-ed81b573e6be/)\n## [A Data Scientist's Guide to Stakeholders](https://towardsdatascience.com/a-data-scientists-guide-to-stakeholders-ed81b573e6be/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow data scientists can best communicate with non-DS people\n[Haden Pelletier](https://towardsdatascience.com/author/pelletierhaden/)\nSeptember 26, 20247 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0GvyMZE1S5JMW5woF-scaled.jpg)](https://towardsdatascience.com/simple-gps-data-visualization-using-python-and-open-street-maps-50f992e9b676/)\n## [Simple GPS data visualization using Python and Open Street Maps](https://towardsdatascience.com/simple-gps-data-visualization-using-python-and-open-street-maps-50f992e9b676/)\n[Data Visualization](https://towardsdatascience.com/category/data-science/data-visualization/)\nThere is an easy way of visualizing the GPS data on the maps.\n[Leo Tisljaric, PhD](https://towardsdatascience.com/author/tisljaricleo/)\nJanuary 31, 20213 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries | Towards Data Science",
    "description": "How to work with Nested Dictionary in Python? This article teaches you everything you need to know about Python Nested Dictionaries.",
    "keywords": null,
    "author": "Dario Radečić",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries",
    "og:description": "How to work with Nested Dictionary in Python? This article teaches you everything you need to know about Python Nested Dictionaries.",
    "og:url": "https://towardsdatascience.com/nested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0WrDTY9iMfUWfmb2R-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1696",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Dario Radečić",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "13 min read",
    "article:published_time": "2023-04-18T12:00:52.000Z",
    "article:modified_time": "2023-04-18T12:00:52.000Z",
    "article:author": "https://towardsdatascience.com/author/radecicdario/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_000.txt",
      "chars": 49
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_001.txt",
      "chars": 483
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_002.txt",
      "chars": 573
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_003.txt",
      "chars": 449
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_004.txt",
      "chars": 255
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_005.txt",
      "chars": 191
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_006.txt",
      "chars": 334
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_007.txt",
      "chars": 56
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_008.txt",
      "chars": 497
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_009.txt",
      "chars": 54
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_010.txt",
      "chars": 69
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_011.txt",
      "chars": 293
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_012.txt",
      "chars": 527
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_013.txt",
      "chars": 495
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_014.txt",
      "chars": 520
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_015.txt",
      "chars": 507
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_016.txt",
      "chars": 611
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_017.txt",
      "chars": 541
    },
    {
      "language": "txt",
      "file": "attachments/bba80bdd6168/code/block_018.txt",
      "chars": 67
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0WrDTY9iMfUWfmb2R-scaled.jpg",
      "alt": "Photo by Kelly Sikkema on Unsplash",
      "local_path": "attachments/bba80bdd6168/images/000.jpg",
      "bytes": 288728,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1gtv8OSh_7HOYevfSkG1zdQ.png",
      "alt": "Image 1 - Nested dictionary of employees (image by author)",
      "local_path": "attachments/bba80bdd6168/images/001.png",
      "bytes": 10308,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1gtv8OSh_7HOYevfSkG1zdQ.png",
      "alt": "Image 2 - Nested dictionary of employees (2) (image by author)",
      "local_path": "attachments/bba80bdd6168/images/002.png",
      "bytes": 10308,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1hFy1cwTlij9CfjSVzCRkuw.png",
      "alt": "Image 3 - Accessing elements of a nested Python dictionary (image by author)",
      "local_path": "attachments/bba80bdd6168/images/003.png",
      "bytes": 3747,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1Q6HGt_9XMNYBcAk7GNuT4A.png",
      "alt": "Image 4 - Changing a single value in a nested dictionary (image by author)",
      "local_path": "attachments/bba80bdd6168/images/004.png",
      "bytes": 4464,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1Mecb7s5V-g8hR3F9opI7nw.png",
      "alt": "Image 5 - Changing multiple values in a nested dictionary (image by author)",
      "local_path": "attachments/bba80bdd6168/images/005.png",
      "bytes": 4738,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/15Y5pGloUDwYZNvpEoN1hRQ.png",
      "alt": "Image 6 - Adding elements to a nested dictionary in Python (image by author)",
      "local_path": "attachments/bba80bdd6168/images/006.png",
      "bytes": 15297,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1TntgZAMCEuFiXcy9uPLXkw.png",
      "alt": "Image 7 - Deleting elements from a nested dictionary (image by author)",
      "local_path": "attachments/bba80bdd6168/images/007.png",
      "bytes": 10492,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1nKjWwmaAQkDZfVnUk1Dz6g.png",
      "alt": "Image 8 - Two new employees (image by author)",
      "local_path": "attachments/bba80bdd6168/images/008.png",
      "bytes": 10753,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1uvWKC8fF51UTziOOjEJDQw.png",
      "alt": "Image 9 - Merging nested dictionaries (image by author)",
      "local_path": "attachments/bba80bdd6168/images/009.png",
      "bytes": 20556,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1uvWKC8fF51UTziOOjEJDQw.png",
      "alt": "Image 10 - Merging nested dictionaries (2) (image by author)",
      "local_path": "attachments/bba80bdd6168/images/010.png",
      "bytes": 20556,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/17TO6BHeApFEr6FEtWsmnMg.png",
      "alt": "Image 11 - Iterating through a nested dictionary (image by author)",
      "local_path": "attachments/bba80bdd6168/images/011.png",
      "bytes": 10433,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1TrW_8P0vzIQI015rJAw8IQ.png",
      "alt": "Image 12 - Iterating through a nested dictionary (2) (image by author)",
      "local_path": "attachments/bba80bdd6168/images/012.png",
      "bytes": 9861,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1WnzIw_UU5UbTyJVnG-aB3A.png",
      "alt": "Image 13 - Flattening a nested dictionary (image by author)",
      "local_path": "attachments/bba80bdd6168/images/013.png",
      "bytes": 10104,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1VG0hMU8hIaXeYAxboG3CbA.png",
      "alt": "Image 14 - Nested dictionary to a Pandas DataFrame (image by author)",
      "local_path": "attachments/bba80bdd6168/images/014.png",
      "bytes": 6554,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/01/0IbRY6w6uR9jRQwCn-scaled.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/015.jpg",
      "bytes": 273144,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/06/svd_with_4_vectors.gif",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/016.gif",
      "bytes": 167337,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0BVBq7eNCvhBJnc_i-scaled.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/017.jpg",
      "bytes": 433156,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/18mwg2tMRuSzs20gCox9aQA.jpeg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/018.jpeg",
      "bytes": 408708,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/04/0_WT4QQ7xSn5fYRUn-scaled.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/019.jpg",
      "bytes": 402726,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0DSfW3MBnqq9JnYtk-scaled.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/020.jpg",
      "bytes": 936324,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0Oq_OdOVeEcDLA98V.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/021.jpg",
      "bytes": 145974,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/09/0udXy6a2qaip0CS9q-scaled.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/022.jpg",
      "bytes": 454223,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0GvyMZE1S5JMW5woF-scaled.jpg",
      "alt": "",
      "local_path": "attachments/bba80bdd6168/images/023.jpg",
      "bytes": 412510,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [
    {
      "src": "https://www.youtube.com/c/TowardsDataScience",
      "quality": "unavailable",
      "local_path": "",
      "note": "无1080p且无720p，未交付更低清晰度"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/radecicdario/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/coding/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/towards-data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/top-3-methods-for-handling-skewed-data-1334e0debf45/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/animating-linear-transformations-with-quiver/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/data-visualization/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/artemij.lehmann/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/practical-guide-to-entity-resolution-part-3-1b2c262f50a7/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@kellysikkema"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://betterdatascience.com/python-dictionaries/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://medium.com/@radecicdario/membership"
    },
    {
      "type": "external",
      "href": "https://betterdatascience.com/nested-dictionary-python/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Nested+Dictionary+Python+-+A+Complete+Guide+to+Python+Nested+Dictionaries&u=https%3A%2F%2Ftowardsdatascience.com%2Fnested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Nested+Dictionary+Python+-+A+Complete+Guide+to+Python+Nested+Dictionaries&url=https%3A%2F%2Ftowardsdatascience.com%2Fnested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Nested+Dictionary+Python+-+A+Complete+Guide+to+Python+Nested+Dictionaries&url=https%3A%2F%2Ftowardsdatascience.com%2Fnested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:48Z",
  "source_url": "https://towardsdatascience.com/nested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}