d = {
 "Laptop": {
            "sony": 1,
            "apple": 2,
            "asus": 5,
          },
 "Camera": {
            "sony": 2,
            "sumsung": 1,
            "nikon" : 4,
           },
}
with open("my.json","w") as f:
    json.dump(d,f)
Answer from Joran Beasley on Stack Overflow
🌐
Quora
quora.com › How-can-we-convert-a-Python-nested-dictionary-to-a-JSON-file
How can we convert a Python nested dictionary to a JSON file? - Quora
To sort keys alphabetically: json.dump(data, f, sort_keys=True, indent=2) ... These steps convert nested Python dictionaries to JSON files reliably, while addressing common needs: readability, encoding, non-serializable types, memory constraints, ...
Discussions

Parsing JSON nested Dictionary using Python - Stack Overflow
I have the following nested Dictionary in JSON. If I want to get "id", "self", "name", how should I parse it using a Python Program. More on stackoverflow.com
🌐 stackoverflow.com
Nested Dictionary for JSON data
Because j is not always dict for key,value in data1.items(): for i,j in value.items(): print(j) for k,l in j.items(): print([key,k,l]) Alaska Traceback (most recent call last): File "C:/Users/xxy/PycharmProjects/tb/test.py", line 16, in for k,l in j.items(): AttributeError: 'str' object has no attribute 'items' More on reddit.com
🌐 r/learnpython
5
1
November 30, 2022
How to reference nested dictionaries through JSON?
sounds like a disaster waiting to happen. u can do it recursively. check key:value exists and value type is a dict. call it on itself. till value isn't a dict no more. then add the next dict? u can probably sent new_dict with the function since doesn't do anything till value isn't a dict no more. then [value] = new_dict don't think u care that much of the names' since can check if its a dict or not. {'a':{'b': ......: 'hh'} then u replace 'hh' with the 'new dict. is this what u meant? More on reddit.com
🌐 r/learnpython
5
3
July 17, 2021
How can i convert python nested dictionary to json file? - Stack Overflow
You can convert your dictionary entries to a list with list(data.values()) and then export it to JSON. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... Modernizing curation: A proposal for The Workshop and The Archive · 7 How to generate a json file in python from nested ... More on stackoverflow.com
🌐 stackoverflow.com
August 31, 2020
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › convert python dictionary to json
Convert Python Dictionary to JSON - Spark By {Examples}
May 31, 2024 - A dictionary inside another dictionary is called a nested dictionary. To convert the nested dictionary into a JSON object, we have to pass the given dictionary and indent param into dumps() function.
🌐
Python Guides
pythonguides.com › convert-dictionary-to-json-python
Convert a Nested Dictionary to JSON in Python
September 8, 2025 - Used json.dumps() to convert the dictionary into a JSON string. Added indent=4 to make the output more readable. This is the method I use most often when I just need a quick and clean conversion. Sometimes, instead of just printing JSON, I need to save it into a .json file.
Top answer
1 of 4
35

To understand how your json is set up, it's easier to break it down. Let's look at the first dictionary's keys, and remove the values.

json = {"items": [], "links": {}}

You have a dictionary with two keys and two values. All three of the variables you are looking for (id, self, name) are in the first key, "items". So let's dive deeper.

json["items"] = [{'links': {'self': 'https://www.google.com'}, 'name': 'beast', 'type': 'Device', 'id': '12345'}]

Now you have a list containing a dictionary with the values you are looking for, so let's enter the first and only value of the list containing the next dictionary.

json["items"][0] = {'links': {'self': 'https://www.google.com'}, 'id': '12345', 'type': 'Device', 'name': 'beast'}

Finally we have the dictionary with the values are looking for, so you can use this code to find name and id.

json["items"][0]["name"] = beast

json["items"][0]["id"] = 12345

The self variable is hidden one dictionary deeper so we have to delve into the links key.

json["items"][0]["links"]["self"] = http://google.com

Now you have all of your values, you just need to follow through all the lists and dictionaries to get the value you want.

2 of 4
3

You can write a function, that will get the values you need:

def dict_get(x,key,here=None):
    x = x.copy()
    if here is None: here = []
    if x.get(key):  
        here.append(x.get(key))
        x.pop(key)
    else:
        for i,j in x.items():
          if  isinstance(x[i],list): dict_get(x[i][0],key,here)
          if  isinstance(x[i],dict): dict_get(x[i],key,here)
    return here

dict_get(a,'id')
 ['12345']

dict_get(a,'self')
 ['https://www.google.com', 'https://www.google.com']

dict_get(a,'name')
['beast']

You can as well call any key that you want:

data

a = {
  "items": [
    {
      "id": "12345",
      "links": {
        "self": "https://www.google.com"
      },
      "name": "beast",
      "type": "Device"
    }
  ],
  "links": {
    "self": "https://www.google.com"
  },
  "paging": {
    "count": 1,
    "limit": 1,
    "offset": 0,
    "pages": 1
  }
}
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to extract nested dictionary data in python?
How to extract Nested Dictionary Data in Python? | Towards Data Science
March 5, 2025 - The course has helped hundreds of students learn to extract nested data. You don’t have to purchase the course to obtain the files. The filenames are single_json.py and multiple_json.py. In this example, we’ll start by extracting data using a combination of list and dictionary extraction techniques as shown in the preceding table. In the Python code below, I start by providing the logic to import the data, the solution and then the workflow to derive the solution.
🌐
Reddit
reddit.com › r/learnpython › nested dictionary for json data
r/learnpython on Reddit: Nested Dictionary for JSON data
November 30, 2022 -
import re, json, requests

url = 'https://raw.githubusercontent.com/Fyresite/US-City-State-Zip-Master-JSON/master/states.json'

resp = requests.get(url)
resp_parsed = re.sub(r'^jsonp\d+\(|\)\s+$', '', resp.text)
data = json.loads(resp_parsed)

print(data.items)
if isinstance(data, dict):
    print(data.items())

for key,value in data.items():
    for i,j in value.items():
        for k,l in j.items():
            print([key,k,l])

I am getting the below error when I am trying to print State, City & Zip code, because this is a nested dictionary where the structure as follows:
( [StateCode , {cities :{ cityName:[Zipcode]}, name:'StateName')])

 AttributeError                            
Traceback (most recent call last) Input In [85], in <cell line: 1>()       
1 for key,value in data.items():       
2 for i,j in value.items(): ----> 
3 for k,l in j.items():       
4 print([key,k,l])  
AttributeError: 'str' object has no attribute 'items' 

Please let me know how can I get the output printed as below:

State City Zip
AK Akhiok 99615

Thank you in advance.

Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › parsing-json-nested-dictionary-using-python
Parsing Json Nested Dictionary Using Python - GeeksforGeeks
July 23, 2025 - In this example, below recursive function (`recursive_parser`) extracts nested values from a Python dictionary (`json_data`) based on a list of keys (`keys_to_extract`).
🌐
Reddit
reddit.com › r/learnpython › how to reference nested dictionaries through json?
r/learnpython on Reddit: How to reference nested dictionaries through JSON?
July 17, 2021 -

I have a nested dictionary inside a JSON file. It contains a header dictionary and one of the values is another dictionary called count. This dictionary gets a new key and value Everytime the program runs. Or at least it was supposed to, but I haven't found a way to reference the actual right value of count{} when running the code. I tried doing this in pickle but it lead to way too many problems. So I'm trying with JSON.

In a nutshell: Have a nested dictionary saved in JSON. The dictionary inside the dictionary needs some name to use as reference inside the program which looks for it when running, and adds a new key-value pair. How do I find the right names for these objects inside objects?

I really need this, any help is appreciated!

🌐
FavTutor
favtutor.com › blogs › dict-to-json-python
5 Ways to Convert Dictionary to JSON in Python | FavTutor
October 5, 2021 - To convert the nested dictionary into a json object, you can use the dumps function itself.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-python-dictionary-to-json
How To Convert Python Dictionary To JSON? - GeeksforGeeks
July 12, 2025 - Dictionaries can have nested structures and json.dumps() effectively handles such cases. With indentation, nested objects remain easy to read, ensuring clarity in complex data structures.
🌐
GitHub
github.com › MrFuguDataScience › JSON › blob › master › Nested Dictionary Example.ipynb
JSON/Nested Dictionary Example.ipynb at master · MrFuguDataScience/JSON
"people_json=df_to_nested_json(un_nested_candidates, cols)\n", "\n", "people_json['features'][:2]\n", "\n", "people_json" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "with open('employee_data.json', 'w') as fp:\n", " json.dump(people_json, fp)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 ·
Author   MrFuguDataScience
🌐
Medium
perfecto25.medium.com › python-dictionaries-get-nested-value-the-sane-way-4052ab99356b
Python Dictor — get a Dictionary/JSON nested value the sane way | by Mike R | Medium
September 16, 2019 - Python Dictor — get a Dictionary/JSON nested value the sane way pip install dictor usage: import json from dictor import dictor with open(‘sample.json’) as data: data = json.load(data) …
🌐
iO Flood
ioflood.com › blog › python-dict-to-json
Convert a Python Dict to JSON | json.dumps() User Guide
January 30, 2024 - In this example, our Python dictionary dict_data has another dictionary as a value. When we use json.dumps(), it processes the nested dictionary just like it would a simple one, converting the entire structure into a JSON object.
🌐
Stack Exchange
codereview.stackexchange.com › questions › 184668 › fast-implementation-to-output-nested-dict-to-json
python - Fast implementation to output nested dict to JSON - Code Review Stack Exchange
September 1, 2018 - def output_conll_retrievals_to_json(output_file, conll_mcs,conll_sentences, num_retrieval): num_sentence = len(conll_sentences) with open(output_file, 'w') as f: for i in range(num_sentence): num_position = len(conll_sentences[i]) level2 = dict() level1 = dict() for j in range(num_position): level0 = dict() for mc in conll_mcs[i][j]: mc_str = ' '.join(mc.mention_string) level0[mc_str] = dict() level0[mc_str]['index'] = mc.mention level0[mc_str]['retrievals'] = self.get_one_mc_retrievals(mc, num_retrieval) level1[conll_sentences[i][j]] = level0 level2[' '.join(conll_sentences[i])] = level1 json.dump(level2, f) f.write('\n')
🌐
Python
bugs.python.org › issue38414
Issue 38414: Ordering a nested dictionary in python with json format - Python tracker
October 8, 2019 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/82595
🌐
Stack Overflow
stackoverflow.com › questions › 66822334 › how-to-write-nested-dictionary-to-json-file
python - How to write nested dictionary to JSON file? - Stack Overflow
from datetime import datetime import json DATE_FMT = '%Y-%m-%d %H:%M' def decode_dict(d): result = {} for key, value in d.items(): if isinstance(key, datetime): key = datetime.strftime(key, DATE_FMT) if isinstance(value, datetime): value = datetime.strftime(value, DATE_FMT) elif isinstance(value, dict): value = decode_dict(value) # Recursive call. result.update({key: value}) return result if __name__ == '__main__': ohlc = {58072071: {datetime(2021, 3, 26, 23, 20): {'high': 179.0, 'low': 179.0, 'open': 179.0, 'close': 179.0, 'volume': 2354}}} print(json.dumps(decode_dict(ohlc))) ... {"58072071": {"2021-03-26 23:20": {"high": 179.0, "low": 179.0, "open": 179.0, "close": 179.0, "volume": 2354}}} } ... Find the answer to your question by asking.
🌐
freeCodeCamp
forum.freecodecamp.org › python
Trouble reading froma nested dictionary - Python - The freeCodeCamp Forum
February 24, 2023 - Hello, I am making API calls that return json data like this - { "basicServiceSets": [ { "ssidName": "My SSID", "ssidNumber": 0, "enabled": true, "band": "2.4…