python中嵌套字典的规范化

发布于 01-15 23:50 字数 1303 浏览 5 评论 0原文

我是 Python 新手,我有一个嵌套字典,我想对其标准化字典的值。例如:

nested_dictionary={'D': {'D': '0.33', 'B': '0.17', 'C': '0.00', 'A': '0.17', 'K': '0.00', 'J': '0.03'}, 'A': {'A': '0.50', 'K': '0.00', 'J': '0.08'}}

我想获得标准化,因为

Normalized_result={'D': {'D': '0.47', 'B': '0.24', 'C': '0.00', 'A': '0.24', 'K': '0.00', 'J': '0.04'}, 'A': {'A': '0.86', 'K': '0.00', 'J': '0.14'}}

我在 标准化字典值 中看到了示例仅适用于一本字典,但我想进一步使用嵌套字典。 我尝试压平nested_dictionary并将标准化应用为

import flatdict
d =  flatdict.FlatDict(nested_dictionary, delimiter='_')
dd=dict(d)
newDict = dict(zip(dd.keys(), [float(value) for value in dd.values()]))

def normalize(d, target=1.0):
    global factor
    raw = sum(d.values())
    print(raw)
    if raw==0:
        factor=0
        #print('ok')
    else:
       # print('kok')
        factor = target/raw
    return {key:value*factor for key,value in d.items()}

normalize(newDict)

我得到的结果为

{'D_D': 0.2578125,
 'D_B': 0.1328125,
 'D_C': 0.0,
 'D_A': 0.1328125,
 'D_K': 0.0,
 'D_J': 0.023437499999999997,
 'A_A': 0.39062499999999994,
 'A_K': 0.0,
 'A_J': 0.06249999999999999}

但我想要的是上面的Normalized_result 提前致谢。

I am new to Python and I have a nested dictionary for which I want to normalize the values of the dictionary. For example:

nested_dictionary={'D': {'D': '0.33', 'B': '0.17', 'C': '0.00', 'A': '0.17', 'K': '0.00', 'J': '0.03'}, 'A': {'A': '0.50', 'K': '0.00', 'J': '0.08'}}

And I would like to get the normalization as

Normalized_result={'D': {'D': '0.47', 'B': '0.24', 'C': '0.00', 'A': '0.24', 'K': '0.00', 'J': '0.04'}, 'A': {'A': '0.86', 'K': '0.00', 'J': '0.14'}}

I have seen the example in Normalizing dictionary values which only for one dictionary but I want to go further with nested one.
I have tried to flatten the nested_dictionary and apply the normalization as

import flatdict
d =  flatdict.FlatDict(nested_dictionary, delimiter='_')
dd=dict(d)
newDict = dict(zip(dd.keys(), [float(value) for value in dd.values()]))

def normalize(d, target=1.0):
    global factor
    raw = sum(d.values())
    print(raw)
    if raw==0:
        factor=0
        #print('ok')
    else:
       # print('kok')
        factor = target/raw
    return {key:value*factor for key,value in d.items()}

normalize(newDict)

And I get the result as

{'D_D': 0.2578125,
 'D_B': 0.1328125,
 'D_C': 0.0,
 'D_A': 0.1328125,
 'D_K': 0.0,
 'D_J': 0.023437499999999997,
 'A_A': 0.39062499999999994,
 'A_K': 0.0,
 'A_J': 0.06249999999999999}

But what I want is the Normalized_result as above
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

记忆消瘦2025-01-22 23:50:21
nested_dictionary = {'D': {'D': '0.33', 'B': '0.17', 'C': '0.00', 'A': '0.17', 'K': '0.00', 'J': '0.03'},
                     'A': {'A': '0.50', 'K': '0.00', 'J': '0.08'}}

在此示例中,您的 dict 值是 str 类型,因此我们需要转换为 float:

nested_dictionary = dict([b, dict([a, float(x)] for a, x in y.items())] for b, y in nested_dictionary.items())

nested_dictionary

{'D': {'D': 0.33, 'B': 0.17, 'C': 0.0, 'A': 0.17, 'K': 0.0, 'J': 0.03},
 'A': {'A': 0.5, 'K': 0.0, 'J': 0.08}}

下面的函数改编自您提供的链接。
它循环遍历字典,计算因子并就地更新值。

for _, d in nested_dictionary.items():
    factor = 1.0/sum(d.values())
    for k in d:
        d[k] = d[k] * factor

nested_dictionary

{'D': {'D': 0.47142857142857136,
  'B': 0.24285714285714285,
  'C': 0.0,
  'A': 0.24285714285714285,
  'K': 0.0,
  'J': 0.04285714285714285},
 'A': {'A': 0.8620689655172414, 'K': 0.0, 'J': 0.13793103448275865}}

如果您需要转换回 str,请使用以下函数:

nested_dictionary = dict([b, dict([a, "{:.2f}".format(x)] for a, x in y.items())] for b, y in nested_dictionary.items())

nested_dictionary

{'D': {'D': '0.47',
  'B': '0.24',
  'C': '0.00',
  'A': '0.24',
  'K': '0.00',
  'J': '0.04'},
 'A': {'A': '0.86', 'K': '0.00', 'J': '0.14'}}
nested_dictionary = {'D': {'D': '0.33', 'B': '0.17', 'C': '0.00', 'A': '0.17', 'K': '0.00', 'J': '0.03'},
                     'A': {'A': '0.50', 'K': '0.00', 'J': '0.08'}}

In this example, your dict values are str type, so we need to convert to float:

nested_dictionary = dict([b, dict([a, float(x)] for a, x in y.items())] for b, y in nested_dictionary.items())

nested_dictionary

{'D': {'D': 0.33, 'B': 0.17, 'C': 0.0, 'A': 0.17, 'K': 0.0, 'J': 0.03},
 'A': {'A': 0.5, 'K': 0.0, 'J': 0.08}}

The function below is adapted from the link you provided.
It loops through the dictionaries, calculates the factor and updates the values inplace.

for _, d in nested_dictionary.items():
    factor = 1.0/sum(d.values())
    for k in d:
        d[k] = d[k] * factor

nested_dictionary

{'D': {'D': 0.47142857142857136,
  'B': 0.24285714285714285,
  'C': 0.0,
  'A': 0.24285714285714285,
  'K': 0.0,
  'J': 0.04285714285714285},
 'A': {'A': 0.8620689655172414, 'K': 0.0, 'J': 0.13793103448275865}}

If you need to convert back to str, use the function below:

nested_dictionary = dict([b, dict([a, "{:.2f}".format(x)] for a, x in y.items())] for b, y in nested_dictionary.items())

nested_dictionary

{'D': {'D': '0.47',
  'B': '0.24',
  'C': '0.00',
  'A': '0.24',
  'K': '0.00',
  'J': '0.04'},
 'A': {'A': '0.86', 'K': '0.00', 'J': '0.14'}}
酒与心事2025-01-22 23:50:21

这段代码可以做到:

def normalize(d, target=1.0):
    raw = sum(float(number) for number in d.values())
    factor = (target/raw if raw else 0)
    return {key: f'{float(value)*factor:.2f}' for key, value in d.items()}


{key: normalize(dct) for key, dct in nested_dictionary.items()}

This code would do:

def normalize(d, target=1.0):
    raw = sum(float(number) for number in d.values())
    factor = (target/raw if raw else 0)
    return {key: f'{float(value)*factor:.2f}' for key, value in d.items()}


{key: normalize(dct) for key, dct in nested_dictionary.items()}
¢好甜2025-01-22 23:50:21
  1. 将内部字典中的字符串值转换为浮点数。
  2. 重复中获取解决方案之一,例如really_safe_normalise_in_place
  3. 在每个字典上使用解决方案。

例子:

d = {'D': {'D': '0.33', 'B': '0.17', 'C': '0.00', 'A': '0.17', 'K': '0.00', 'J': '0.03'}, 'A': {'A': '0.50', 'K': '0.00', 'J': '0.08'}}
d = {k: {kk: float(vv) for kk, vv in v.items()} for k, v in d.items()}
for v in d.values():
    really_safe_normalise_in_place(v)
  1. Turn the string-values in your inner dicts into floats.
  2. Take one of the solutions from the the duplicate, for example really_safe_normalise_in_place.
  3. Use the solution on each dict.

Example:

d = {'D': {'D': '0.33', 'B': '0.17', 'C': '0.00', 'A': '0.17', 'K': '0.00', 'J': '0.03'}, 'A': {'A': '0.50', 'K': '0.00', 'J': '0.08'}}
d = {k: {kk: float(vv) for kk, vv in v.items()} for k, v in d.items()}
for v in d.values():
    really_safe_normalise_in_place(v)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文