Python Forum
[nested dics] Easy way to find if a key exists?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[nested dics] Easy way to find if a key exists?
#1
Hello,

I'm using xmltodict to work with XML files. It turns data into nested dictionaries.

In nested dictionaries that don't contain the same keys, I can't find an easy way to simply check if any given key exists somewhere.

The following functions don't work as expected:
def f(d, keys):
    if not keys:
        return True
    return keys[0] in d and f(d[keys[0]], keys[1:])
	
def keys_exists(element, *keys):
    '''
    Check if *keys (nested) exists in `element` (dict).
    '''
    if not isinstance(element, dict):
        raise AttributeError('keys_exists() expects dict as first argument.')
    if len(keys) == 0:
        raise AttributeError('keys_exists() expects at least two arguments, one given.')

    _element = element
    for key in keys:
        try:
            _element = _element[key]
        except KeyError:
            return False
    return True
Is there a way besides looping?

Thank you.

   
Reply


Messages In This Thread
[nested dics] Easy way to find if a key exists? - by Winfried - Sep-17-2020, 01:29 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] [Beautifulsoup] Find if element exists, and edit/append? Winfried 2 7,164 Sep-03-2022, 10:14 PM
Last Post: Winfried
  Python Program to Find the Total Sum of a Nested List vlearner 8 8,310 Jan-23-2022, 07:20 PM
Last Post: menator01
  p]Why os.path.exists("abc/d") and os.path.exists("abc/D") treat same rajeev1729 1 2,778 May-27-2020, 08:34 AM
Last Post: DeaD_EyE
  Easy way to sort a nested dict Alfalfa 3 6,544 Dec-07-2018, 04:12 PM
Last Post: Alfalfa

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020