使用dpath库替换具有特定键的子字典。

huangapple go评论60阅读模式
英文:

Substituting sub-dictionaries with specific keys using dpath library

问题

{  "a": {
    "b": {
      "Red": 随机_0_1之间的随机数,
      "Green": 随机_1_10之间的随机数
    },
    "c": {
      "Red": 随机_2_100之间的随机数
    }
  }
}
英文:

I have a nested input dictionary in this form:

{  "a": {
    "b": {
      "Red": {"min": 0, "max": 1},
      "Green": {"min": 1, "max": 10}
    },
    "c": {
      "Red": {"min": 2, "max": 100}
    }
  }
}

I would like to use the dpath library to search for all the sub-dictionaries in the form {'min': min_value, 'max': max_value} and substitute all such sub-dictionaries with a random number between min_value and max_value.

Expected output

{  "a": {
    "b": {
      "Red": random_number_between_0_and_1,
      "Green": random_number_between_1_and_10
    },
    "c": {
      "Red": random_number_between_2_and_100
    }
  }
}

Note that the code should be as general as possible, as the sub-dict with min/max keys could be at any level in the dictionary. I've been trying to use the regex option of dpath, but I was not able to make good use of it for this application.

答案1

得分: 0

我使用dpath进行了筛选来找到这个解决方案,尽管我希望使用正则表达式而不是筛选来得到更紧凑的解决方案:

import dpath, random

d = { "a": {
    "b": {
      "Red": {"min": 0, "max": 1},
      "Green": {"min": 1, "max": 10}
    },
    "c": {
      "Red": {"min": 2, "max": 100}
    }
  }
}

def find_minmax(x):
    if 'min' in str(x) or 'max' in str(x):
        return True
    return False

for path, value in dpath.search(d, '*/*/*', afilter=find_minmax, yielded=True):
    dpath.set(d, path, random.uniform(value['min'], value['max']))
    
print(d)

Output:

{'a': {'b': {'Red': 0.9707850659514508, 'Green': 4.074090994331721}, 'c': {'Red': 55.14734187097105}}}
英文:

I found this solution using filtering with dpath, although I would like a more compact solution using regex, instead of filtering:

import dpath, random

d = {  "a": {
    "b": {
      "Red": {"min": 0, "max": 1},
      "Green": {"min": 1, "max": 10}
    },
    "c": {
      "Red": {"min": 2, "max": 100}
    }
  }
}

def find_minmax(x):
    if 'min' in str(x) or 'max' in str(x):
        return True
    return False

for path, value in dpath.search(d, '*/*/*', afilter=find_minmax, yielded=True):
    dpath.set(d, path, random.uniform(value['min'], value['max']))
    
print(d)

Output:

{'a': {'b': {'Red': 0.9707850659514508, 'Green': 4.074090994331721}, 'c': {'Red': 55.14734187097105}}}

huangapple
  • 本文由 发表于 2023年6月16日 15:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76488007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定