在Python中查找具有字符值的嵌套Dict的最大值

2024-04-29 03:15:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一句话:

{'children': [{'children': [{'criteria': ['United Kingdom'],
     'name': ['3'],
     'prediction': ['0.256'],
     'weights': ['604']},
    {'criteria': ['United States'],
     'name': ['4'],
     'prediction': ['0.231'],
     'weights': ['5316']}],
   'criteria': ['United Kingdom United States'],
   'name': ['2'],
   'prediction': ['0.233'],
   'variableNames': ['Country name'],
   'weights': ['5920']},
  {'children': [{'criteria': [' Brazil Canada'],
     'name': ['6'],
     'prediction': ['0.153'],
     'weights': ['10029']},
    {'criteria': ['France Germany Spain Turkey'],
     'name': ['7'],
     'prediction': ['0.053'],
     'weights': ['1335']}],
   'criteria': [' Brazil Canada France Germany Spain Turkey'],
   'name': ['5'],
   'prediction': ['0.141'],
   'variableNames': ['Country name'],
   'weights': ['11364']}],
 'criteria': ['l 1'],
 'name': ['1'],
 'prediction': ['0.173'],
 'variableNames': ['Country name'],
 'weights': ['17284']}

我需要找到两个预测和权重的最大值和最小值,这两个值都是字符类型,所以我需要两者都将它们转换为Float/int,然后找到它们的max/min值,同时遍历所有键/值。在

通过使用一些previs很好的问题,我发现如果int的值有效:

^{pr2}$

这和我把值转换成int/float差不多:

for body in test:
     test[body]['prediction'] = float(test[body]['prediction'])
     test[body]['weights'] = int(test[body]['weights'])

这又抛出了一个类似的错误。在


Tags: nametestbodycountryunitedkingdomintprediction
2条回答

你需要遍历递归函数

def maxr(D, k):
    return max([float(D[k][0])] + [maxr(i, k) for i in D.get('children', [])])

输出

^{pr2}$

您可以类似地定义函数minr

如果你想要的是某个特定字段的最大值,那么John的解决方案很好,但是我认为有一个递归生成每个字典的生成器会更灵活。在

def iter_children(data):
    yield data
    for child in data.get('children', []):
        for c in iter_children(child):  # if you're using Python3 "yield from" can simplify this
            yield c


print max(float(c['prediction'][0]) for c in iter_children(raw_data))
print max(int(c['weights'][0]) for c in iter_children(raw_data))

那么,只要“巴西”在标准中,就很容易得到最大预测。在

^{pr2}$

相关问题 更多 >