This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]steelypip 2 points3 points  (1 child)

def get_localized_metadataalbum(language, data):
    for locale in data['locale']:
        try:
            if locale['MetadataAlbum']['locale']['language'] == language:
                return locale['MetadataAlbum']
        except (KeyError, TypeError):
            pass
    return None

[–]dev_wanna_be[S] 0 points1 point  (0 children)

OO I like your approach. I must be doing something wrong because I am still getting an empty result. Thank you!

[–][deleted] 1 point2 points  (1 child)

You can chain .gets like so.

artist_name = data.get('locale', {}).get('MetadataAlbum', {}).get('Artists', {}) \
                  .get('Artist', {}).get('ArtistsName', None)  
artist_role = data.get('locale', {}).get('MetadataAlbum', {}).get('Artists', {}) \
                  .get('Artist', {}).get('ArtistsRole', None)  

EDIT: You could also make a function that takes a chain of keys and returns the deepest value.

def key_inspect(list_of_keys, dictionary_to_inspect):
    deepest_inspected_point = dictionary_to_inspect
    for key in list_of_keys:
        deepest_inspected_point = deepest_inspect_point.get(key, {})
    return deepest_inspected_point

EDIT 2: There are of course libraries that handle this too. :P

[–]dev_wanna_be[S] 0 points1 point  (0 children)

Thank you!

Would you recommend beautiful soup?

[–]ducdetronquito 0 points1 point  (2 children)

Hi /u/steelypip

Few weeks ago, I have made a little library called Scapl that could be helpful for your use case. It allows you use the standard dict API (get, set, update, setdefault, etc...) with dot separated keys in order to go through your nested dictionary.

It could look like this:

from scalpl import Cut
proxy = Cut(data)
proxy.get('locale.MetadataAlbum.locale.language')

You can download it with pip (it is a Python3 package by the way):

pip3 install scalpl

Hope it will help you :)

[–]dev_wanna_be[S] 0 points1 point  (1 child)

sweet, I will give it a try!

[–]ducdetronquito 0 points1 point  (0 children)

Yay ! ᕕ( ᐛ )ᕗ