Get value from list of nested dict in Python based on key

python get nested dictionary keys
python get all values from nested dictionary
python find value in nested dictionary
nested dictionary python for loop
python get value from dictionary if key exists
python list of dictionaries get value
create nested dictionary python for loop
remove key from nested dictionary python

I have a list of dict, need to get the int_value from the sub-dict of values based on the value of the key.

my_list = [{'key': 'previous_id',
  'value': {'int_value': '-4343583665607944462'}},
 {'key': 'event_origin', 'value': {'string_value': 'auto'}},
 {'key': 'screen_id', 'value': {'int_value': '-5880567181845583757'}},
 {'key': 'previous_class', 'value': {'string_value': 'MainActivity'}},
 {'key': 'screen', 'value': {'string_value': 'Gateway'}},
 {'key': 'screen_class', 'value': {'string_value': 'Gateway'}}]

For example, I need to get -4343583665607944462 as a string output for previous_id.

This is what I got so far, which looks over complicated to me, want to know if there is more straightforward way to achieve that.

for d in my_list:
    if list(d.values())[0] == 'previous_id':

Get -4343583665607944462 as a string output for previous_id.

Please also suggest if define a function would make sense.

It may be worth while to preprocess your initial list of dicts, something like:

key_to_int = {}
for d in my_list:
    if 'int_value' in d['value']:
        key_to_int[d['key']] = d['value']['int_value']
        key_to_int[d['key']] = None

You can then simply do:


Which outputs:


The above assumes all your dicts follow the same format. In the case where some dicts may be nested deeper than others, some modifications need to be made.

Python Nested Dictionary, To create a nested dictionary, simply pass dictionary key:value pair as keyword to combine separate lists of keys and values obtained dynamically at runtime. To avoid such exception, you can use the special dictionary get() method. Use the built-in update() method to merge the keys and values of one nested� from jsonpath_rw import parse def nested_get(d, path): result = parse(".".join(path)).find(d) return result[0].value if result else None Some code style notes about your current approach: Python functions does not follow the camel case naming conventions, put an underscore between words - nested_get() instead of nestedGet()

I'd suggestion checking if the first value is "previous_id" by using the "key" key rather than .values()[0], and same for getting the value. If you know the keys ahead of time, this is the recommended way of accessing data from a dictionary.

If you want to simplify your code, you could use the next function, which loops over an iterable and returns the first value it finds (that matches the given condition if there is one).

For example:

value = next(d["value"] for d in my_list if d["key"] == "previous_id")

This would return

{'int_value': '-4343583665607944462'}

If you want just "-4343583665607944462", then you could do:

value = next(list(d["value"].values())[0] for d in my_list if d["key"] == "previous_id")

Note here we use .values()[0] because the keys are not always the same.

Also next raises a StopIteration exception if it reaches the end of the iterable without finding a match so consider wrapping it in a try/except block.

Python Nested Dictionary (With Examples), Unless I'm missing something you'd like to implement, I would go for a simple loop instead of using recursion: def nested_get(input_dict, nested_key):� Let’s see how to get the key by value in Python Dictionary. Method #1: Using list.index() The index() method returns index of corresponding value in a list. Below is an implementation how to use index() method to fetch Dictionary key using value.

I don't know if you have access to modifying the actual list beforehand, but it would probably make more sense to keep the type of value inside a single dict e.g:

my_list = [{
    'key': 'previous_id',
    'value': '-4343583665607944462',
    'type': 'int_value' },...]

This way you could simply call:

for dict in my_list:
    if dict['key']=='previous_id':
        return dict['value']

or a one-liner:

value = [x['values'] for x in my_list if x['key']=='previous_id']

and if you are keen on having the value type

value = {x['type']:x['values'] for x in my_list if x['key']=='previous_id'}

Get value from dictionary given a list of nested keys, Consider adhering more strictly to Python naming conventions. Fetching a list of values by key from a dictionary is a task that should work for� Sometimes, we may require a way in which we have to get all the values of specific key from a list of dictionary. This kind of problem has a lot of application in web development domain in which we sometimes have a json and require just to get single column from records.

If you would like use the same dictionary and stick with your method, you can use:

for d in my_list:
    if d["key"] == 'previous_id':

But would recommend you to use a dictionary like this:

my_dict = {"previous_id": '-4343583665607944462', 'event_origin':'auto',  
    'screen_id':-5880567181845583757,  'previous_class': 'MainActivity',
    'screen': 'Gateway',  'screen_class': 'Gateway'}

Then you can use print simply like this:


Getting a key's value in a nested dictionary, Python - Inner Nested Value List Mean in Dictionary � Python | Sum values for each key in nested dictionary � Python | Sort nested dictionary by� The above example finds the value of the key “one” of Dictionary in Python. This gives value in Dictionary for the single key given. However, to get more values with the keys, you have to use the get function again. Find the Value Using Index Operator in Python. In addition to the above method, you can also get the values by keys in

Python, Thanks for your nice example. I changed it a bit for my use case, where I needed to get all contained keys of a nested iterable as a list (also for the values) as can� Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys’ values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records.

Find all occurences of a key in nested python dictionaries and lists , Get all keys or values of a nested dictionary or list in Python. def iterate_all(iterable, returned="key"):. """Returns an iterator that returns all� Use data.items() to iterate through your dictionary's keys and values rather than only keys. This allows cleaner syntax to access values. Make your function more general for maximum reusability. Fetching a list of values by key from a dictionary is a task that should work for any key. Why not make "PLU" a search parameter?

Get all keys or values of a nested dictionary or list in Python � GitHub, Another data type exists in Python to store multiple data which is called List. The list works Next, for loop is used to read the value of each key of the nested dictionary. # Create a Example-4: Delete data based on key from nested dictionary. In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. nested_dict = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}} Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value.

  • for dict_ in my_list:..if dict_['key'] == 'previous_id':....yield dict_['value']['int_value'] ?
  • Thanks for the reply. I ended up making a method to preprocess the list with input of list and value type, so that I can use the same to get int_value and string_value.