繁体   English   中英

如何使用另一个嵌套字典中的值更新嵌套字典中的值

[英]How to update values in a nested dictionary using values from another nested dictionary

Stackoverflow 的新手,如果标题不清楚,请道歉。

实际上,我正在使用两个 xl 到 CSV 文件,它们都使用方法to_dict转换为嵌套字典,其中 index 是每个(主?)字典的键,列是每个嵌套字典的键。

IE

 DICTA = {0: {x:1, y:2, v:3}, 1: {x:5, y:6, v:7}, 2: {x:8, y:9, v:10}}

 DICTB = {0: {a:3, b:12, c:13, d:14}, 1: {a:15, b:16, c:17, d:18}, 2: {a:19, b:20, c:21, d:22}}

以上示例的值是任意的(两个字典的长度始终相同,嵌套字典的键数不同)

DICT B 中的每个嵌套字典只能用于一次更新嵌套 DICT A 字典,即 DICT A 中的每个嵌套字典“属于”DICT B 中的嵌套字典,但不以任何特定顺序。

如果满足其他条件/值,我的目标是使用来自 Dict B 的值(键是两者的差异)更新 Dict A 中的值(嵌套字典)。即我到目前为止:

for k, v in DICTA.items():
i=0
h=0
  if DICTA[i].get('v') in (DICTB[h].get('a'), (DICTB[h].get('b')):
    if (DICTB[h].get('a') != '15': #another condition I need to put in
        DICTA[i].update({'x': DICTB[h].get('c')}) 
        DICTA[i].update({'y': DICTB[h].get('d')})
        i+=1 
    else:
        DICTA[i].update({'y': DICTB[h].get('c')}) 
        DICTA[i].update({'x': DICTB[h].get('d')})
        i+=1
  else:
      h+=1

实际 output:

In: DICTA

Out: {0: {x:13, y:14, v:3}, 1: {x:5, y:6, v:7}, 2: {x:8, y:9, v:10}}

上述预期的 Output:

In: DICTA

Out: {0: {x:13, y:14, v:3}, 1: {x:18, y:17, v:7}, 2: {x:21, y:22, v:10}}

我的问题是这适用于第一个 DICTA 条目,但随后无法更新接下来的两个,即这显然没有正确更新 i 或 h 以循环遍历下一个嵌套字典。

完全意识到上述内容可能是痛苦的非 Pythonic,并且非常愿意接受更简单的方法来解决这个问题。

谢谢大家对上述任何帮助表示感谢。

如果我理解正确,这应该有效:

for row_a, row_b in zip(DICTA.values(), DICTB.values()):
    if row_a.get('v') in (row_b.get('a'), row_b.get('b')):
        if row_b.get('a') != '15':
            row_a.update({
                'x': row_b.get('c'), 
                'y': row_b.get('d')
            })
        else:
            row_a.update({
                'y': row_b.get('c'), 
                'x': row_b.get('d')
            })

也代替:

row_a.update({
    'x': row_b.get('c'), 
    'y': row_b.get('d')
})

你可以使用:

row_a['x'] = row_b.get('c')
row_a['y'] = row_b.get('d')

但这是一个偏好问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM