That seems generally fine.

There's no need to first read the file, then use loads. You can just use load directly.

output_json = json.load(open('/tmp/output.json'))

Using i and k isn't correct for this. They should generally be used only for an integer loop counter. In this case they're keys, so something more appropriate would be better. Perhaps rename i as container and k as stream? Something that communicate more information will be easier to read and maintain.

You can use output_json.iteritems() to iterate over both the key and the value at the same time.

for majorkey, subdict in output_json.iteritems():
    print majorkey
    for subkey, value in subdict.iteritems():
            print subkey, value

Note that, when using Python 3, you will need to use items() instead of iteritems(), as it has been renamed.

Answer from chmullig on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › using python to loop through json dictionary that re-uses the same key?
r/learnpython on Reddit: Using Python to loop through JSON dictionary that re-uses the same key?
October 13, 2022 -

I'm trying to restructure JSON output from a API to the specific format that Ansible wants for it's invetory file. To do this I thought I would loop through the JSON and grab the variables I need and then feed that into the proper structure. However, I noticed my API JSON is using the same $ key for multiple variables. How can I properly reference and differentiate between the variables? Here is an example:

 "model-responses": {
        "model": [
            {
                "@mh": "0x11e013",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch1"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "Raritan Computer, Inc.DV"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.1"
                    },
                    {
                        "@id": "0x10052",
                        "$": "PX2 030610"
                    }
                ]
            },
            {
                "@mh": "0x115014",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch2"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "DCS-7010T-48"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.2"
                    },
                    {
                        "@id": "0x10052",
                        "$": "Arista Networks EOS version 4.22.3M-INT running on an Arista Networks DCS-7010T-48"
                    }
                ]
            },
Discussions

Help Iterate Python - Json file
Can you help me iterate over this Json file ?to have the ‘name’ { “data”: [ { “circulating_supply”: 18556575, “cmc_rank”: 1, “date_added”: “2013-04-28T00:00:00.000Z”, “id”: 1, “last_updated”: “2020-11-28T10:13:02.000Z”, “max_supply”: 21000000, “name”: ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
November 28, 2020
How to iterate through this dictionary (dictionary/list within the dictionary)?

What you're looking at is called 'json'. It's basically xml with javascript friendly syntax.

It's more or less the modern standard for sending data to and from apis. Python has a built in tool to work with it: https://docs.python.org/2/library/json.html

Let's call your data json_raw

import json
json_dict = json.loads(json_raw)

From here json_dict is a python dictionary object that represents that data. It uses dict syntax to access the data:

for example: json_dict['teams'] gets the teams json_dict['teams'][0]['_links']['fixtures']['href'] would return "http://api.football-data.org/alpha/teams/66/fixtures"

you can iterate through dictionaries:

for team in json_dict['teams']:
    print team['_links']['fixtures']['href']

should output each fixtures url

edit:

SEE https://gist.github.com/bionikspoon/d7014741472e43f41a25

I was just playing with it. Something sparked my curiosity. But this works.

More on reddit.com
🌐 r/learnpython
4
2
August 16, 2015
python - Iterating through a JSON object - Stack Overflow
Unfortunately it's a little hard ... and dictionaries and strings in the 600 characters you can put in a comment. I already said you should index the dict to get at the value associated with a key. I'm not sure what you want to iterate over. Learning about built-in Python types is the next step. 2010-04-28T23:52:06.653Z+00:00 ... There's not much iteration involved when you want to get individual items. Perhaps what you want to iterate over is json_object, not ... More on stackoverflow.com
🌐 stackoverflow.com
Looping over a nested dictionary (from json file) and creating a new dictionary with some omissions - need help
You don't need the get_keys function: stuff = {1:10, 2:20, 3:30} stuff_list = list(stuff) Reading the rest, I am losing the sense of what you are trying to do. If you want to loop through the outer dictionary, just: for key, value in outer.items(): So value will be a dictionary, which you can step through in the same way with an inner loop: for inner_key, inner_value in value.items(): if conditions: new_dictionary[inner_key] = inner_value BUT, you can just add the one dictionary to another dictionary: orignal_dictionary.update(extra_dictionary) and, as you've already used, you can use dictionary comprehension to generate in-situ that extra_dictionary (with appropriate filters in comprehension). More on reddit.com
🌐 r/learnpython
5
1
November 26, 2019
🌐
Tech-otaku
tech-otaku.com › mac › using-python-to-loop-through-json-encoded-data
Using Python to Loop Through JSON-Encoded Data – Tech Otaku
For example, the releases list for macOS Mojave contains seven values (dictionaries), but for macOS Catalina contains only six. To overcome this we can use a for statement to loop or iterate through every value in the list repeating the same steps during each loop or iteration.
🌐
Quora
quora.com › How-do-I-loop-through-a-JSON-file-with-multiple-keys-sub-keys-in-Python
How to loop through a JSON file with multiple keys/sub-keys in Python - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
Delft Stack
delftstack.com › home › howto › python › iterate through json python
How to Iterate Through JSON Object in Python | Delft Stack
February 2, 2024 - During each iteration, the loop prints out the current key, followed by a colon, and the corresponding value obtained by accessing the dictionary with json_data[key]. Finally, when the code is executed, the output will display the keys and values ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › loop-through-a-json-array-in-python
Loop through a JSON array in Python - GeeksforGeeks
July 23, 2025 - You can loop through a JSON array in Python by using the json module and then iterating through the array using a for loop.
🌐
CodeSpeedy
codespeedy.com › home › how to loop through json with subkeys in python
How to loop through JSON with subkeys in Python - CodeSpeedy
January 20, 2020 - {"website":"codespeedy","topic":"json and python","no_of_posts":{"year2019":15,"year2020":5}} To iterate through JSON with keys, we have to first import the JSON module and parse the JSON file using the ‘load’ method as shown below. import json with open('json_multidimensional.json','r') as string: my_dict=json.load(string) string.close() It will parse the ‘json_multidimensional.json’ file as the dictionary ‘my_dict’.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-through-nested-json-object-using-python
Iterate Through Nested Json Object using Python - GeeksforGeeks
July 23, 2025 - In this example, the below Python code utilizes `json.dumps` to flatten a nested JSON object into a string and then uses `json.loads` to convert it back into a dictionary. It then iterates through the flattened dictionary, printing key-value pairs.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Help Iterate Python - Json file - Curriculum Help - The freeCodeCamp Forum
November 28, 2020 - Can you help me iterate over this Json file ?to have the ‘name’ { “data”: [ { “circulating_supply”: 18556575, “cmc_rank”: 1, “date_added”: “2013-04-28T00:00:00.000Z”, “id”: 1, “last_updated”: “2020-11-28T10:13:02.000Z”, “max_supply”: 21000000, “name”: “Bitcoin”, “num_market_pairs”: 9550, “platform”: null, “quote”: { “USD”: { “last_updated”: “2020-11-28T10:13:02.000Z”, “market_cap”: 315363411475.37506, “percent_change_1h”: -0.09085874, “percent_change_24h”: -0.96244779, “percen...
🌐
py4u
py4u.org › blog › python-read-json-and-loop-dictionary
Python: How to Read JSON and Loop Through a Dictionary – Correct Methods Explained for Beginners
JSON arrays become Python lists. If you try to loop through a list like a dictionary, you’ll get a TypeError.
🌐
EyeHunts
tutorial.eyehunts.com › home › loop through json python
Loop through JSON Python
June 26, 2023 - Then, we define a JSON object as a string in the json_data variable. We use json.loads() to parse the JSON string into a Python object, which is stored in the data variable. This object becomes a dictionary in this case.
🌐
Reddit
reddit.com › r/learnpython › how to iterate through this dictionary (dictionary/list within the dictionary)?
r/learnpython on Reddit: How to iterate through this dictionary (dictionary/list within the dictionary)?
August 16, 2015 -

I've got my dictionary of scraped data here, I was wondering how I can take this and return the data I want from it?

I just want to return the inner dictionary (so 'links, code, cresturl, name, etc') and I'm a bit confused about the structure of this as I haven't found the right question to google...

edit: well this is a stupid question. How do I return the "teams" list/dictionary specifically? It looks like a dictionary within a list because of the syntax [ { } ]

{
    "_links": [
        {
            "self": "http://api.football-data.org/alpha/soccerseasons/354/teams"
        }, 
        {
            "soccerseason": "http://api.football-data.org/alpha/soccerseasons/354"
        }
    ], 
    "count": 20, 
    "teams": [
        {
            "_links": {
                "fixtures": {
                    "href": "http://api.football-data.org/alpha/teams/66/fixtures"
                }, 
                "players": {
                    "href": "http://api.football-data.org/alpha/teams/66/players"
                }, 
                "self": {
                    "href": "http://api.football-data.org/alpha/teams/66"
                }
            }, 
            "code": "MUFC", 
            "crestUrl": "http://upload.wikimedia.org/wikipedia/de/d/da/Manchester_United_FC.svg", 
            "name": "Manchester United FC", 
            "shortName": "ManU", 
            "squadMarketValue": "425,000,000 \u20ac"
        }, 
        {
            "_links": {
                "fixtures": {
                    "href": "http://api.football-data.org/alpha/teams/72/fixtures"
                }, 
                "players": {
                    "href": "http://api.football-data.org/alpha/teams/72/players"
                }, 
                "self": {
                    "href": "http://api.football-data.org/alpha/teams/72"
                }
            }, 
            "code": "SWA", 
            "crestUrl": "http://upload.wikimedia.org/wikipedia/de/a/ab/Swansea_City_Logo.svg", 
            "name": "Swansea City", 
            "shortName": "Swans", 
            "squadMarketValue": "104,000,000 \u20ac"
        }, 
        {
            "_links": {
                "fixtures": {
                    "href": "http://api.football-data.org/alpha/teams/338/fixtures"
                }, 
                "players": {
                    "href": "http://api.football-data.org/alpha/teams/338/players"
                }, 
                "self": {
                    "href": "http://api.football-data.org/alpha/teams/338"
                }
            }, 
            "code": "LCFC", 
            "crestUrl": "http://upload.wikimedia.org/wikipedia/en/6/63/Leicester02.png", 
            "name": "Leicester City", 
            "shortName": "Foxes", 
            "squadMarketValue": "63,250,000 \u20ac"
        }, 
        {
            "_links": {
                "fixtures": {
                    "href": "http://api.football-data.org/alpha/teams/62/fixtures"
                }, 
                "players": {
                    "href": "http://api.football-data.org/alpha/teams/62/players"
                }, 
                "self": {
                    "href": "http://api.football-data.org/alpha/teams/62"
                }
            }, 
            "code": "EFC", 
            "crestUrl": "http://upload.wikimedia.org/wikipedia/de/f/f9/Everton_FC.svg", 
            "name": "Everton FC", 
            "shortName": "Everton", 
            "squadMarketValue": "179,250,000 \u20ac"
        },  
        .... etc
         }
      ]
 }
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-loop-through-a-json-file-with-multiple-keys-sub-keys-in-python
How can I loop over entries in JSON using Python?
For example, if you have a json with the following content − · { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } You can load it in your python program and loop over its keys in the following way −
🌐
Red And Green
redandgreen.co.uk › home › python code
Nested Dictionaries - Red And Green
February 13, 2023 - import json # The 'real' code used ... We loop through the outer dictionary, finding the key:value pairs, and then using the second for loop we iterate through the key:value pairs from the returned values of the outer dictionary...
🌐
Reddit
reddit.com › r/learnpython › looping over a nested dictionary (from json file) and creating a new dictionary with some omissions - need help
r/learnpython on Reddit: Looping over a nested dictionary (from json file) and creating a new dictionary with some omissions - need help
November 26, 2019 -

Hello fellow Pythonians!

I'm working on repurposing a library and have run into a hitch that I could use some help with.

I've got a json file that I've brought in as a dictionary of dictionaries of dictionaries (so double-nested). I need to loop through the variables, get a list of the keys, then loop through those keys, get the key-value-pairs of the innerstats.

Here's what I have so far (assume the json file is already loaded):

def get_keys(dict):
    keys = []
    for key in dict.keys():
        keys.append(key)
    return keys

variable_keys = get_keys(variable_data)

Which gets me a list of the outer keys.

Now I need to loop through the outer keys and get the KVPs with some omissions, so I have:

def create_dict():
new_dict = {}
for keys in variable_keys:
    new_dict.update({k: v for k, v in variable_data[keys].items() if k not in ['omit1', 'omit2', 'omit3']})
return new_dict

variable_table = create_dict()

But this is only returning 1 of the variables and not the full dictionary of variables.

I've been banging my head against this for a couple of hours so any help would be appreciated.

Top answer
1 of 2
1
You don't need the get_keys function: stuff = {1:10, 2:20, 3:30} stuff_list = list(stuff) Reading the rest, I am losing the sense of what you are trying to do. If you want to loop through the outer dictionary, just: for key, value in outer.items(): So value will be a dictionary, which you can step through in the same way with an inner loop: for inner_key, inner_value in value.items(): if conditions: new_dictionary[inner_key] = inner_value BUT, you can just add the one dictionary to another dictionary: orignal_dictionary.update(extra_dictionary) and, as you've already used, you can use dictionary comprehension to generate in-situ that extra_dictionary (with appropriate filters in comprehension).
2 of 2
1
Instead of this: def get_keys(dict): keys = [] for key in dict.keys(): keys.append(key) return keys variable_keys = get_keys(variable_data) You can just write: variable_keys = variable_data.keys() Or if you absolutely need the keys as a list: variable_keys = list(variable_data.keys()) Moving on, in this function: def create_dict(): new_dict = {} # I assume you meant to indent this for keys in variable_keys: You refer to variable_keys, which is defined outside the context of this function. Instead, let's pass the list of keys (or the list of whatever, as far as this function needs to be concerned) as an argument: def create_dict(values_list): new_dict = {} for keys in values_list: Reading the next line: new_dict.update({k: v for k, v in variable_data[keys].items() if k not in ['omit1', 'omit2', 'omit3']}) Okay, that line is much too long - 107 characters; 79 is a good standard. I'm going to fix it with an opinionated autoformatter called black so that I can read it. (You don't have to use black, just showing you my process; but you probably should avoid writing lines that are that long). $ black your-script.py Now it looks like: new_dict.update( { k: v for k, v in variable_data[keys].items() if k not in ["omit1", "omit2", "omit3"] } ) Little better. Okay, so what is variable_data? The dict from the original JSON? Again, it's not good for functions to refer to data that exist outside of those functions. Let's rewrite this to just take variable_data as an argument (which for this function, I will call input_dict) and output the updated version of the dict. We can use a dict comprehension to write your code more simply: def create_dict(input_dict): omissions = ("omit1", "omit2", "omit3") # Doesn't need to be a list; a tuple (like a list, but immutable) is fine return { key: value for key, value in input_dict.items() if key not in omissions } variable_table = create_dict(variable_data) If you don't like comprehensions, you can write the loop explicitly and it will do exactly the same thing: def create_dict(input_dict): omissions = ("omit1", "omit2", "omit3") output_dict = {} for key, value in input_dict.items(): if key not in omissions: output_dict[key] = value return output_dict
🌐
Reddit
reddit.com › r/learnpython › best way to iterate through nested json?
r/learnpython on Reddit: Best way to iterate through nested JSON?
December 6, 2020 -

My Json is of the following format:

https://pastebin.com/KUKHHh2e

The numbers in this json are many as are the dates. I am trying to iterate through this to create a single list of dictionaries that contains all of the information in the dictionary that is 3 layers deep in the json.

I have made a loop that is n3 but it seems highly inefficient given i have around 30,000 iterations to make.

What are my options here?

🌐
Python Forum
python-forum.io › thread-39669.html
Loop through json file and reset values [SOLVED]
March 23, 2023 - Hello everybody, I have a json file which stores information for different people, which looks like this: { "person": }Everytime my script get's executed I want to select a random person. Once the per
🌐
Inductive Automation
forum.inductiveautomation.com › ignition
Looping through JSON - Ignition - Inductive Automation Forum
December 8, 2021 - Hello all, I have a script transform on a dataset that is bound to the instance of a flex repeater: In the first part of the code, I am returning 6 instances with their values from the dataset, now I would like to be able to return an index value for each instance just like the picture below: I am new to JSON and I do not know how to combine the last part with the first part of the code.
🌐
Claudia Kuenzler
claudiokuenzler.com › blog › 1395 › how-to-iterate-nested-json-dict-search-specific-value-print-key-python
How to iterate through a nested JSON, search for a specific value and print the key with Python
February 27, 2024 - The first line (printing the full JSON) worked, but then the for loop failed miserably. The TypeError message doesn't make sense to a occasional Python script writer like me - but research revealed the reason behind the TypeError: we are trying to access a value using a key within another key and that’s leading to the occurrence of the error. The key is of the type string and not dict. In other words: Python is parsing through ...