0

I want to filter the specified value in the dictionary by inputting a dynamic key string. How to deal with dynamic key string?

if key string like filter_key = "fdd.hello1" or filter_key = "fdd.hello1.k1.k2.k3"

import operator as op


d1 = {'name': 'test1',
        'with_child': ['c1', 'c2'],
        'fdd': {'hello1': 123, 'hello2': 234},
        'date': '2023-3-10'}

filter_key = "fdd.hello1"


def filter_value(val, filter_key):
    dot_count = op.countOf(filter_key, ".")
    filter_value = ""

    try:
        if dot_count == 0:
            filter_value = d1[filter_key]
        if dot_count == 1:
            f1,c1 = filter_key.split(".")
            filter_value = d1[f1][c1]
        elif dot_count == 2:
            f1,c1,c2 = filter_key.split(".")
            filter_value = d1[f1][c1][c2]
    except KeyError as e:
        print("123213123213")
    return filter_value
Ershan
  • 623
  • 8
  • 9
  • 1
    It's not clear what you mean by `filter out`. Are you trying to remove that key/value pair from the dict or get the value? It would help if you showed an input and desired output. – Mark Mar 06 '23 at 04:52
  • The posted duplicate will do what you want if you make a list of keys by splitting your string on `.` – Nick Mar 06 '23 at 05:21

1 Answers1

1

The key is to split the string and then loop through the result:

def dict_deep_get(dct, path):
    target = dct
    *_path, name = path.split('.')
    for p in _path:
        target = target[p]
    return target[name]

Amir
  • 1,871
  • 1
  • 12
  • 10