简体   繁体   中英

Check a key exist in entire list or dict in python

I am creating dict in python and this dict may includes lists and sub dicts . If I want to check a key exist in any dict first I have reach to that dict and then only I can check wether the key exists or not . But is there any way that I can check key existence using parent dict only means if parent dict have any child dicts then searching goes to every level and let me know that wether the key exist in entire dict or not and then using that key I can insert or delete elments in that dict which includes that key.

eg, I have this

[
    {
        'groupName': u'MainMenu_1',
        'menuItems': [
            {
                'action': u'/home\r\n',
                'sub_1': [

                ],
                'id': 1L,
                'name': u'Home\r\n'
            },
            {
                'action': u'/inventory',
                'sub_2': [

                ],
                'id': 2L,
                'name': u'Inventory\r\n'
            },
            {
                'action': u'/accounting\r\n',
                'sub_3': [
                    {
                        'action': u'/gl\r\n',
                        'name': u'GL\r\n',
                        'sub_4': [

                        ]
                    },
                    {
                        'action': u'/ap\r\n',
                        'name': u'AP\r\n',
                        'sub_5': [

                        ]
                    },
                    {
                        'action': u'/ar\r\n',
                        'sub_6': [

                        ],
                        'name': u'AR\r\n'
                    }
                ],
                'id': 3L,
                'name': u'Accounting\r\n'
            },
            {
                'action': u'/crm\r\n',
                'sub_8': [

                ],
                'id': 8L,
                'name': u'CRM\r\n'
            }
        ]
    },
    {
        'groupName': u'MainMenu_2',
        'menuItems': [
            {
                'action': u'/iv-receive\r\n',
                'sub_9': [

                ],
                'id': 9L,
                'name': u'Receiving\r\n'
            },
            {
                'action': u'/iv-shipping\r\n',
                'sub_10': [

                ],
                'id': 10L,
                'name': u'Shipping\r\n'
            }
        ]
    }
]

Now if in above example I want to search for any key like sub_1 , sub_3, sub_6 then how I can search for this key

We can search for all qualifying dictionary recursively. The following implementation appends all references of such dictionaries to the list found :

def recursive_search(items, key):
    found = []
    for item in items:
        if isinstance(item, list):
            found += recursive_search(item, key)
        elif isinstance(item, dict):
            if key in item:
                found.append(item)
            found += recursive_search(item.values(), key)
    return found

found = recursive_search(items, 'sub_9')
def flatten(obj):
    if isinstance(obj, list):
        result = set()
        for e in obj:
            result = result.union(flatten(e))
        return result
    elif isinstance(obj, dict):
        return set(obj.keys()) | flatten(obj.values())
    else:
        return {obj}

You can alternatively flatten the list/dictionary into a set, and do as many searches as you want quickly.

print(flatten(lst))
set([1, 2, 3, u'/inventory', 8, 9, 'menuItems', u'/home\r\n', u'/ar\r\n', u'AP\r\n', u'/accounting\r\n', 'id', u'MainMenu_2', u'Receiving\r\n', u'Home\r\n', u'MainMenu_1', u'/iv-shipping\r\n', 'groupName', 10, u'AR\r\n', u'Accounting\r\n', u'/ap\r\n', u'Inventory\r\n', u'CRM\r\n', u'/crm\r\n', u'/iv-receive\r\n', 'sub_10', u'GL\r\n', u'Shipping\r\n', 'name', 'sub_2', 'sub_3', 'sub_1', 'sub_6', 'sub_4', 'sub_5', 'action', 'sub_8', 'sub_9', u'/gl\r\n'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM