0

I have a dictionary like this:

I saw this question Find all occurrences of a key in nested python dictionaries and lists, but it's return all the values of key.

{
  "html": {
    "head": {
      "title": {
        "text": "Your Title Here"
      }
    },
    "body": {
      "bgcolor": "FFFFFF",
      "img": {
        "src": "clouds.jpg",
        "align": "bottom",
        "text": ""
      },
      "a": [
        {
          "href": "http://somegreatsite.com",
          "text": "Link Name"
        },
        {
          "href": "mailto:support@yourcompany.com",
          "text": "support@yourcompany.com"
        }
      ],
      "p": [
        {
          "text": "This is a new paragraph!dasda"
        },
        {
          "h1": {
            "text": "dasda"
          }
        }
        {
          "h3": {
            "text": "hello therereere"
          }
        }
      ],
      "h1": [
        {
          "text": "This is a Header"
        },
        {
          "class": "text-primary",
          "text": "This is a Header"
        }
      ],
      "h2": {
        "text": "This is a Medium Header"
      },
      "b": {
        "text": "This is a new sentence without a paragraph break, in bold italics.",
        "i": {
          "text": "This is a new sentence without a paragraph break, in bold italics."
        }
      }
    }
  }
}

I want to function just find the first occurrence of key

for example:

if i search for h1 return:

{"text": "dasda"}

2 Answers2

0

Should be noted your question is constructed a bit weirdly. Technically the first occurrence of h1 (in regards to hierarchy) is under html.body.h1. You seem to want to find the very first occurrence in the dictionary in regards to order, so in other words, you are looking for html.body.p.h1. However, a dictionary in Python does not guarantee order for most versions.

Here is a hierarchical solution for the time being:

def func(dictionary: dict, key: str):
    a = None
    for k, v in dictionary.items():
        if key in dictionary:
            return dictionary[key]
        elif isinstance(v, dict):
            a = func(v, key)

    if isinstance(a, list):
        return a[0]
    else:
        return a

print(func(a, "h1"))

Outputs:

{'text': 'This is a Header'}
felipe
  • 7,324
  • 2
  • 28
  • 37
0

You can do this recursively:

# Recursively go through dicts and lists to find the given target key
def findKey(target, dic):
    found = False

    # No iteration if it is a string
    if isinstance(dic, str):
        return None

    # Iterate differently if it is a list
    if isinstance(dic, list):
        for elem in dic:
            found = findKey(target, elem)
            if (found):
                return found
        return found

    # Find the key in the dictionary
    for key in dic.keys():
        if (key == target):
            return dic[key]
        else:
            found = findKey(target, dic[key])   
        if (found):
            return found

d = {'html': {'head': {'title': {'text': 'Your Title Here'}}, 'body': {'bgcolor': 'FFFFFF', 'img': {'src': 'clouds.jpg', 'align': 'bottom', 'text': ''}, 'a': [{'href': 'http://somegreatsite.com', 'text': 'Link Name'}, {'href': 'mailto:support@yourcompany.com', 'text': 'support@yourcompany.com'}], 'p': [{'text': 'This is a new paragraph!dasda'}, {'h1': {'text': 'dasda'}}, {'h3': {'text': 'hello therereere'}}], 'h1': [{'text': 'This is a Header'}, {'class': 'text-primary', 'text': 'This is a Header'}], 'h2': {'text': 'This is a Medium Header'}, 'b': {'text': 'This is a new sentence without a paragraph break, in bold italics.', 'i': {'text': 'This is a new sentence without a paragraph break, in bold italics.'}}}}}
findKey("h1", d)

Output:

{'text': 'dasda'}
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43