Search for a key in a nested Python dictionary

后端 未结 2 1540
感情败类
感情败类 2020-11-27 06:54

I have some Python dictionaries like this:

A = {id: {idnumber: condition},.... 

e.g.

A = {1: {11 : 567.54}, 2: {14 : 123.1         


        
2条回答
  •  囚心锁ツ
    2020-11-27 07:30

    dpath to the rescue.

    http://github.com/akesterson/dpath-python

    dpath lets you search by globs, which will get you what you want.

    $ easy_install dpath
    >>> for (path, value) in dpath.util.search(MY_DICT, '*/11', yielded=True):
    >>> ... # 'value' will contain your condition; now do something with it.
    

    It will iterate out all of the conditions in the dictionary, so no special looping constructs required.

    See also

    • how do i traverse nested dictionaries (python)?
    • How to do this - python dictionary traverse and search
    • Access nested dictionary items via a list of keys?
    • Find all occurrences of a key in nested python dictionaries and lists
    • Traverse a nested dictionary and get the path in Python?
    • Find all the keys and keys of the keys in a nested dictionary
    • Searching for keys in a nested dictionary
    • Python: Updating a value in a deeply nested dictionary
    • Is there a query language for JSON?
    • Chained, nested dict() get calls in python

提交回复
热议问题