Home > Software design >  find matching string pattern in nested dict
find matching string pattern in nested dict

Time:02-26

I have a list of list where some can be empty, some contain one dict, and some has dicts where the key data has mixed type str, ints, dict.

[[],
 [{'label': '0', 'data': {'text': ['pattern']}}],
 [{'label': '0', 'data': {'text': ['pattern']}},
  {'label': '1', 'data': 'a1s2'},
  {'label': '9', 'data': 'adf21'},
  {'label': '4', 'data': ''},
  {'label': '6', 'data': '6250000000'},
  {'label': '700', 'data': 2100000}]
]

How to filter and return the index of the list that matches a specific ['pattern'] ?

Expected output:
1, 2

CodePudding user response:

Perhaps a list comprehension could work:

out = [i for i, li in enumerate(lst) for d in li if isinstance(d.get('data'), dict)
       and d['data'].get('text') == ['pattern']]

Output:

[1, 2]

CodePudding user response:

while one liners are really cool, I personally find them a bit harder to read, here a version with multiple lines

index = [] 
for i, li in enumerate(lst): 
   for d in li: 
       if type(d["data"]) == dict: 
           if d["data"]["text"][0] == "pattern": 
               print(d) 
               index.append(i) 
print(index)
  • Related