-2

just wondering, before I start to work on a function. I always like to hear some pythonic solutions.

I am trying to get keys and values from nested dictionaries:

for an example:

a = {'one': {'animal': 'chicken'}, 
     'two': {'fish': {'sea':'shark'}}}

is there any pythonic way to get values from nested dictionary? Like get straight to value of 'fish'?

Thanks in advance

Joshua
  • 40,822
  • 8
  • 72
  • 132
Testing man
  • 677
  • 1
  • 12
  • 28
  • 2
    `a['two']['fish']` doesn't suffice? – Dimitris Fasarakis Hilliard Nov 29 '16 at 11:48
  • 1
    What kind of output would you want exactly?? – blue_note Nov 29 '16 at 11:50
  • the output type doesn't matter... i would just like to avoid a['something']['somethingelse']['fish']... i would like to go straight to dictionary and get the value... – Testing man Nov 29 '16 at 11:53
  • Then store the values differently. Maybe combine the dictionaries in second layer to kick out the first layer, so you get a shallower one? – Peter Smit Nov 29 '16 at 11:54
  • 1
    *"i would just like to avoid `a['something']['somethingelse']['fish']`"* why create a dictionary if you want to avoid getting values by key? – Dimitris Fasarakis Hilliard Nov 29 '16 at 11:54
  • the problem is i get data, which has a lot of nested dictionaries... i need to organise this first... – Testing man Nov 29 '16 at 11:56
  • Then how do you need to organize it? Do you need to flatten it? – Dimitris Fasarakis Hilliard Nov 29 '16 at 11:59
  • It's a lot of useless data whithin this nested dictionaries... what i need is to find only dictionary 'fish' or 'sea' or whatever... i pull this data out for further analysis – Testing man Nov 29 '16 at 12:01
  • It's still not totally clear what you're trying to do. What's the expected return from your function given the `a` in the question? – PM 2Ring Nov 29 '16 at 12:02
  • I have list of dictionary keys for which i am interested. The problem is: i have a lot of data and it would be not practical to use method a['blabla']['blabla']['bingo'] to seach within dictionary. Instead i am looking for a pythonic solution to get straight to value of needed item. and I am really open for any ideas, which are simple and get me value in simple way – Testing man Nov 29 '16 at 12:05
  • view [flatten-nested-python-dictionaries-compressing-keys](http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys) and [access-nested-dictionary-items-via-a-list-of-keys](http://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys) – Jose Ricardo Bustos M. Nov 29 '16 at 12:10
  • Do you want to just search for the key `'fish'` and get that value wherever it is, without having to know what the preceding keys are? – Alex Hall Nov 29 '16 at 12:15
  • Thanks Jose, good ideas. Yes Alex, something like that. – Testing man Nov 29 '16 at 12:37

1 Answers1

0

If you want to find all the items with the "fish" key in the nested dictionary, you can modify this answer flatten nested python dictionaries-compressing keys - answer @Imran

import collections
def get_by_key_in_nested_dict(d, key, parent_key='', sep='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if key==k:
            items.append((new_key, v))
        if isinstance(v, collections.MutableMapping):
            items.extend(get_by_key_in_nested_dict(v, key, new_key, sep).items())
    return dict(items)

with,

test = {
    'one': {
        'animal': 'chicken'
    }, 
    'two': {
        'fish': {
            'sea':'shark', 
            'fish':0
        }
    }, 
    'fish':[1,2,3]
}

get_by_key_in_nested_dict(test,"fish")

You get all the items that have the key "fish"

{
    'fish': [1, 2, 3],
    'two_fish': {'fish': 0, 'sea': 'shark'},
    'two_fish_fish': 0
}
Community
  • 1
  • 1
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62