w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.

The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.

import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)

# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()] 

# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None

Answer from Gabio on Stack Overflow
🌐
Like Geeks
likegeeks.com › home › python › how to get json value by key in python
How To Get JSON Value by Key in Python
Using the get() method to access values provides a safer alternative to direct key access. This method is useful in handling cases where a key might not exist in the JSON object, thus avoiding potential KeyError exceptions.
Top answer
1 of 2
2

w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.

The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.

import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)

# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()] 

# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None

2 of 2
2

The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.

w = None
for item in y['filters']:
    if 'filterB' in item:
        w = item['filterB']
        break

print(w) # val1

Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried

all_dict = dict()
for item in y['filters']:
    all_dict.update(item)

# Replace the list of dicts with the dict
y['filters'] = all_dict

w = y['filters']['filterB']
print(w) # val1

If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:

y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
    if 'filterB' in item:
        all_w.append(item['filterB'])

Or, as a list-comprehension:

all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']

Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension

Discussions

python - How to parse json to get all values of a specific key within an array? - Stack Overflow
I'm having trouble trying to get a list of values from a specific key inside an json array using python. Using the JSON example below, I am trying to create a list which consists only the values of... More on stackoverflow.com
🌐 stackoverflow.com
Getting values from JSON using Python - Stack Overflow
If you need to get a value of a dictionary in a list, then you will need to index the list for the dictionary first to get the value. This is an easy mistake to make especially if an API returns a JSON array with a single object in it. More on stackoverflow.com
🌐 stackoverflow.com
How to get data from json array by python - Stack Overflow
I have following json object data, how can I using python to get both "BuildId" and second "ftp" (note: it is within "ArchiveLocation") value? {"BuildId":"4c53575f-36f48a7f1f37", "Eve... More on stackoverflow.com
🌐 stackoverflow.com
Accessing data from a json array in python - Stack Overflow
Usually the json will be a string ... in python are typically are made up of maps and arrays). so assuming your response is actually a string (eg that was retrieved from a HTTP request/endpoint) then you deserialise it with json.loads (the function is basically load from string), then you've got a map with a 'password' key, that is an ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-do-you-get-all-values-by-key-with-JSON-and-Python
How to get all values by key with JSON and Python - Quora
... Use the recursive generator for most cases; switch to jsonpath-ng for expressive queries or ijson for very large files. ... You can use the json library in Python to get values associated with a key in a JSON object.
🌐
DEV Community
dev.to › bluepaperbirds › get-all-keys-and-values-from-json-object-in-python-1b2d
Get all keys and values from json object in Python - DEV Community
January 12, 2021 - Using load function json file, this let me keep it into a variable called data. ... Then you have a Python object. Now you can get the keys and values. The code below depends on what your json file looks like.
Top answer
1 of 3
18

You cannot do contents[:]["name"] since contents is a list is a dictionary with integer indexes, and you cannot access an element from it using a string name.

To fix that, you would want to iterate over the list and get the value for key name for each item

import json
contents = []

try:
    with open("./simple.json", 'r') as f:
        contents = json.load(f)
except Exception as e:
    print(e)


li = [item.get('name') for item in contents]
print(li)

The output will be

['Bulbasaur', 'Ivysaur']
2 of 3
6

This is not a real answer to the question. The real answer is to use a list comprehension. However, you can make a class that allows you to use specifically the syntax you tried in the question. The general idea is to subclass list so that a slice like [:] returns a special view (another class) into the list. This special view will then allow retrieval and assignment from all the dictionaries simultaneously.

class DictView:
    """
    A special class for getting and setting multiple dictionaries
    simultaneously. This class is not meant to be instantiated
    in its own, but rather in response to a slice operation on UniformDictList.
    """
    def __init__(parent, slice):
        self.parent = parent
        self.range = range(*slice.indices(len(parent)))

    def keys(self):
        """
        Retreives a set of all the keys that are shared across all
        indexed dictionaries. This method makes `DictView` appear as
        a genuine mapping type to `dict`.
        """
        key_set = set()
        for k in self.range:
            key_set &= self.parent.keys()
        return key_set

    def __getitem__(self, key):
        """
        Retreives a list of values corresponding to all the indexed
        values for `key` in the parent. Any missing key will raise
        a `KeyError`.
        """
        return [self.parent[k][key] for k in self.range]

    def get(self, key, default=None):
        """
        Retreives a list of values corresponding to all the indexed
        values for `key` in the parent. Any missing key will return
        `default`.
        """
        return [self.parent[k].get(key, default) for k in self.range]

    def __setitem__(self, key, value):
        """
        Set all the values in the indexed dictionaries for `key` to `value`.
        """
        for k in self.range:
            self.parent[k][key] = value

    def update(self, *args, **kwargs):
        """
        Update all the indexed dictionaries in the parent with the specified
        values. Arguments are the same as to `dict.update`.
        """
        for k in self.range:
             self.parent[k].update(*args, **kwargs)


class UniformDictList(list):
    def __getitem__(self, key):
        if isinstance(key, slice):
            return DictView(self, key)
        return super().__getitem__(key)

Your original code would now work out of the box with just one additional wrap in UniformDictList:

import json
try:
    with open("./simple.json", 'r') as f:
        contents = UniformDictList(json.load(f))
except Exception as e:
    print(e)

print(contents[:]["name"])
🌐
PYnative
pynative.com › home › python › json › python check if key exists in json and iterate the json array
Python Check if key exists in JSON and iterate the JSON array
May 14, 2021 - Check if the key exists or not in JSON using Python. Check if there is a value for a key. Return default value if the key is missing in JSON. Iterate JSON array in Python.
🌐
Medium
medium.com › @sharath.ravi › python-function-to-extract-specific-key-value-pair-from-json-data-7c063ecb5a15
Python function to extract specific key value pair from json data. | by Sharath Ravi | Medium
April 6, 2023 - import json def extract_key_value(json_data, key): """Extracts a specific key-value pair from a JSON data""" data = json.loads(json_data) value = data.get(key) return value · In this example, the function extract_key_value takes two arguments: ...
🌐
Python Guides
pythonguides.com › json-data-in-python
How To Get Values From A JSON Array In Python?
November 29, 2024 - Let me show you another way to extract values from a JSON array is: by using list comprehension. List comprehension allows you to create a new list based on an existing list or iterable. Here’s an example: import json # Load JSON data from file with open('C:/Users/fewli/Downloads/Python/states.json') as file: data = json.load(file) state_names = [state['name'] for state in data] print("State Names:", state_names)
Find elsewhere
🌐
Robotastemtraining
robotastemtraining.com › read › how-do-you-get-all-values-by-key-with-json-and-python
How Do You Get All Values by Key with JSON and Python?
key_to_extract = 'name' values = get_values_by_key(data, key_to_extract) print(values) For the provided JSON data and the key 'name', the output will be:
🌐
CopyProgramming
copyprogramming.com › howto › how-to-get-key-and-value-of-array-json-in-python
Python: Obtaining Key-Value Pairs from a JSON Array in Python: A Guide
May 11, 2023 - new_lst = [] for i in json_array: for name, array in i.items(): value = ''.join(str(array)) result = name+value new_lst.append(result) print(new_lst) ... ["Clothes[{'id': '32705111', 'describes': 'no problem'}]", "Dress[{'id': '32705111', 'describes': 'no outfit'}]"] ... json_arr = [ { 'Clothes': [ { 'id': '32705111', 'describes': 'no problem' } ] }, { 'Dress': [ { 'id': '32705111', 'describes': 'no outfit' } ] } ] for d in json_arr: for name, array in d.items(): globals()[name] = array · Get keys from json in python, How can I write a python program which will give me the keys ['d','e','g']. What I tried is: What I tried is: jsonData = request.json() #request is having all the response which i got from api c = jsonData['c'] for i in c.keys(): key = key + str(i) print(key) Usage exampleprint get_simple_keys(jsonData['c'][0])Feedback
Top answer
1 of 2
1

You can "find" the element in the interface list via a list-comprehension, and fetch the label from that element. For instance:

label = [x['label'] for x in parsed_dict['interface'] if x['id'] == 'testkey'][0]

If you cannot assume that the relevant id exists, then you can wrap this in a try-except, or you can get a list of the labels and validate that it isn't of length 0, or whatever you think would work best for you.

key = 'testkey'
labels = [x['label'] for x in parsed_dict['interface'] if x['id'] == key]
assert len(labels) > 0, f"There's no matching element for key {key}"
label = labels[0]  # Takes the first if there are multiple such elements in the interface array

And while you're at it, you might want to explicitly deal with there being multiple elements with the same id, etc.


Clarification regarding your error(s): parsed_dict["interface"] is a list, so you can index it with ints (and slices and stuff, but that's besides the point), and not with strings.
Each of the list elements is a dict, with two keys: id and label, so even if you were to take a specific element, say -

el = parsed_dict["interface"][0]

you still couldn't do el['testkey'], because that's a value of the dict, not a key.

You could check if the id is the one you're looking for though, via -

if el['id'] == 'testkey':
    print('Yup, this is it')
    label = el['label']

In fact, the single line I gave above is really just shorthand for running over all the elements with a loop and doing just that...

2 of 2
1

You need to browse through all the values and check if it matches expected value. Because values are not guaranteed to be unique in a dictionary, you can't simply refer to them directly like you do with keys.

print([el for el in d["interface"] if "testkey" in el.values()])
🌐
pythontutorials
pythontutorials.net › blog › how-to-parse-json-to-get-all-values-of-a-specific-key-within-an-array
How to Parse JSON in Python to Get All Values of a Specific Key Within an Array? — pythontutorials.net
Parsing JSON in Python to extract values from a specific key in an array is a fundamental skill for data processing. By using Python’s json module (with loads() for strings and load() for files), you can convert JSON into Python dictionaries/lists and then traverse these structures to collect values.
🌐
Safe Community
community.safe.com › data-7 › extract-json-key-value-array-5070
extract json key value array - FME Community - Safe Software
April 26, 2018 - I have a json array in the structure · [{"name":"A","content":"X"},{"name":"B","content":"Y"},{"name":"C","content":"Z"}] how do I extract it as the name/content (key/value) pair so that end up with a feature containing the following attributes: A: X · B: Y · C: Z · In the actual data there are about 40 attributes, so an automatic flatenning of some sort would be prefered. Best answer by takashi · PythonCaller (the json module) import json def processFeature(feature): for m in json.loads(feature.getAttribute('_json')): feature.setAttribute(m['name'], m['content']) XMLXQueyrExtractor (XML Input: None (File is specified in query)) for $m in jn:members(fme:get-json-attribute('_json')) return fme:set-attribute($m('name'), $m('content')) The XQuery processor "Zorba" bundled with FME supports the JSONiq extension.
🌐
Plain English
plainenglish.io › blog › extracting-specific-keys-values-from-a-messed-up-json-file-python-dfb671482681
Extracting Specific Keys/Values From A Messed-Up JSON File (Python)
Then add all values that are either lists or dictionaries back into queue so we can search them again later. If current is a list, we add everything inside current back into queue, so we can search the individual elements later. This can be done using the .extend method. Repeat steps 1–4 until queue is empty. def extract(data, keys): out = [] queue = [data] while len(queue) > 0: current = queue.pop(0) if type(current) == dict: for key in keys: # CHANGE THIS BLOCK if key in current: out.append({key:current[key]}) for val in current.values(): if type(val) in [list, dict]: queue.append(val) elif type(current) == list: queue.extend(current) return outx = extract(data, ["videoID"]) print(x)