简体   繁体   English

在嵌套循环中更新字典

[英]update dictionary in nested loop

I am having trouble updating a dictionary.我在更新字典时遇到问题。 i am just extracting certain fields within each key - but the output is not as expected.我只是在每个键中提取某些字段 - 但 output 与预期不同。 data, expected output and code are below.数据,预期 output 和代码如下。 Thanks for looking, i appreciate any comments感谢观看,感谢任何评论

categories = {'categories_a1' : [{'group': '13GH9', 'number': '1'},{'group': '17KPO', 'number': '73'}, {'group': '26BN11', 'number': '2'}, {'group': '813W', 'number': '99'}],
              'categories_a2' : [{'group': '99ITY', 'number': '12'},{'group': 'JH871', 'number': '15'}, {'group': 'OLH83', 'number': '99'}, {'group': '44RTQ', 'number': '1'}]} 

xpected= {'categories_a1' : [{'13GH9': '1'},{'17KPO':'73'}, {'26BN11':'2'}, {'813W': '99'}],
              'categories_a2' : [{'99ITY':'12'},{'JH871': '15'}, {'OLH83': '99'}, {'44RTQ':'1'}]} 
        

out={}
for k in categories.keys():
    for i in categories[k]:
        x = {k: v for k, v in zip([i['group']], [i['number']])}
    out[k] = x
out.update(out)

One approach:一种方法:

for key, value in categories.items():
    categories[key] = [{ d["group"] : d["number"] }  for d in value]

print(categories)

Output Output

{'categories_a1': [{'13GH9': '1'}, {'17KPO': '73'}, {'26BN11': '2'}, {'813W': '99'}], 'categories_a2': [{'99ITY': '12'}, {'JH871': '15'}, {'OLH83': '99'}, {'44RTQ': '1'}]}

Let's first clean up some general weirdness:让我们首先清理一些普遍的怪异之处:

out.update(out)

This line does effectively nothing and should be omitted.这条线实际上什么也没做,应该被省略。

x = {k: v for k, v in zip([i['group']], [i['number']])}

This makes little sense;这没有什么意义; we create lists with one element each and iterate over them in parallel.我们创建每个包含一个元素的列表并并行迭代它们。 We could just as easily just use those values directly: x = {i['group']: i['number']} .我们可以很容易地直接使用这些值: x = {i['group']: i['number']}

After swapping that in, let's consider the part that causes the actual problem:将其换入后,让我们考虑导致实际问题的部分:

for i in categories[k]:
    x = {i['group']: i['number']}
out[k] = x

The problem here is that you want out[k] to constitute a list of all of the modified dictionaries, but x is repeatedly being assigned one of those dictionaries, and the result then becomes out[k] .这里的问题是您希望out[k]构成所有已修改字典的列表,但x被反复分配其中一个字典,然后结果变为out[k] What you presumably intended to do is repeatedly append those dictionaries to a new empty list:你大概打算做的是重复 append 那些字典到一个新的空列表:

x = []
for i in categories[k]:
    x.append({i['group']: i['number']})
out[k] = x

However, it's clear that you're already familiar and comfortable with comprehensions, and this is an ideal place to use one:但是,很明显您已经熟悉并熟悉推导式,这是使用推导式的理想场所:

out[k] = [{i['group']: i['number']} for i in categories[k]]

And, of course, we can extend this technique to the overall loop:当然,我们可以将此技术扩展到整个循环:

out = {
    k: [{i['group']: i['number']} for i in v]
    for k, v in categories.items()
}

Please carefully study the structure of this code and make sure you understand the technique.请仔细研究此代码的结构并确保您了解该技术。 We have a source dictionary that we want to transform to create our output, and the rule is: the key remains unchanged, the value (which is a list) undergoes its own transformation.我们有一个要转换的源字典来创建我们的 output,规则是:键保持不变,值(这是一个列表)进行自己的转换。 So we start by writing the skeleton for a dict comprehension, using .items() to give us key-value pairs:因此,我们首先编写 dict 理解的框架,使用.items()为我们提供键值对:

out = {
    k: # we need to fill in something to do with `v` here
    for k, v in categories.items()
}

Then we figure out what we're doing with the value: each element of the list is a dictionary;然后我们弄清楚我们在用这个值做什么:列表的每个元素都是一个字典; the way that we process the list is iterative (each element of the input list tells us an element to use in the output list), but the processing of those elements is not (we look at exactly two hard-coded values from that dict, and make a dict from them).我们处理列表的方式是迭代的(输入列表的每个元素都告诉我们要在 output 列表中使用的元素),但这些元素的处理不是(我们从该字典中查看两个硬编码值,并从他们那里听写)。 Given an element i of the list, the corresponding dict that we want has exactly one key-value pair, which we can compute as {i['group']: i['number']} .给定列表的一个元素i ,我们想要的对应dict恰好有一个键值对,我们可以计算为{i['group']: i['number']} So we wrap a list comprehension around that: [{i['group']: i['number']} for i in v] ;所以我们围绕它包装了一个列表理解: [{i['group']: i['number']} for i in v] ; and we insert that into the dict comprehension skeleton, giving us the final result.我们将它插入到 dict 理解框架中,给我们最终的结果。

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

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