将字典字段分组在一起Python

时间:2018-07-05 02:35:08

标签: python python-3.x python-2.7

因此,我将这本词典作为不同查询的输出:

process.env.NODE_ENV

之所以这样做,是因为'qty','pass'和'failed'中的每一个都有不同的查询并附加到数组中。

有什么办法可以将它们组合在一起并放入此表单?取决于他们的索引?

[{"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12},
{"qty": 12}, {"fail": 0, "pass": 12}, {"fail": 0, "pass": 12},
{"fail": 1}, {"pass": 11}, {"fail": 1}, {"pass": 11}, {"fail": 1},
{"pass": 11}, {"fail": 2}, {"pass": 10}]

非常感谢您。

4 个答案:

答案 0 :(得分:4)

更新

感谢UltraInstinctMankind_008的提醒,下面提供了一个更为简化和内在的答案:

lst = [{"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12}, {"fail": 0, "pass": 12},
       {"fail": 0, "pass": 12}, {"fail": 1}, {"pass": 11}, {"fail": 1}, {"pass": 11}, {"fail": 1}, {"pass": 11},
       {"fail": 2}, {"pass": 10}]

# separate dictionaries with different keys
# dictionaries containing both "fail" and "pass" keys will be split
# and fitted into "fail_group" and "pass_group" respectively
qty_group = ({key: _} for dic in lst for key, _ in dic.items() if key == "qty")
fail_group = ({key: _} for dic in lst for key, _ in dic.items() if key == "fail")
pass_group = ({key: _} for dic in lst for key, _ in dic.items() if key == "pass")

# merge dictionaries with keys "qty", "fail" and "pass" item-wisely.
# and print result 
print(list({**x, **y, **z} for (x, y, z) in zip(qty_group, fail_group, pass_group)))

请注意,{**x, **y, **z}仅适用于PEP 448中引入的python> = 3.5。对于python 2或python <3.5,您必须定义自定义函数以执行与{**x, **y, **z}相同的操作(更多详细信息将在this thread中进行讨论):

def merge_three_dicts(x, y, z):
    m = x.copy()
    n = y.copy()
    z.update(x)
    z.update(y)
    return z

因此在这种情况下,代码的最后一行应该是:

print(list(merge_three_dicts(x, y, z) for (x, y, z) in zip(qty_group, fail_group, pass_group)))

上述两种方法都会为您提供结果:

[{'qty': 12, 'fail': 0, 'pass': 12}, {'qty': 12, 'fail': 0, 'pass': 12}, {'qty': 12, 'fail': 1, 'pass': 11}, {'qty': 12, 'fail': 1, 'pass': 11}, {'qty': 12, 'fail': 1, 'pass': 11}, {'qty': 12, 'fail': 2, 'pass': 10}]

答案 1 :(得分:2)

维护多个单独的列表,而不是从查询中追加一个列表,这样您就可以获取单独列表的索引句柄。

例如:

list1 = [{"qty": 12}, {"qty": 12},]
list2 = [{"fail": 0, "pass": 12}, {"fail": 0, "pass": 12},]

map(lambda (ix, el): el.update(list2[ix]), enumerate(list1))

现在list1将包含[{"qty": 12,"fail": 0, "pass": 12},... ]

答案 2 :(得分:1)

这是您的词典列表。有些使用[fail, pass]作为键,有些仅使用[fail]或仅使用[pass]作为键。不知道这是否有意。

dictList = [{"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12}, {"qty": 12},
{"qty": 12}, {"fail": 0, "pass": 12}, {"fail": 0, "pass": 12},
{"fail": 1}, {"pass": 11}, {"fail": 1}, {"pass": 11}, {"fail": 1},
{"pass": 11}, {"fail": 2}, {"pass": 10}]

我的代码从这里开始

failpassList = [] #To keep track of `["fail", "pass"]`
qtyList = [] #To keep track of `["qty"]`

tempDict = {}
checkNext = 0

for index in range(0, len(dictList)):

    #This is the case when, I've seen a key called `fail`, 
    #and now I'm seeing a `pass` right after `fail`, so I will 
    #bring `fail` and `pass` together as keys of a single dictionary.
    #Once this is done, it to `failpassList`

    if checkNext == 1:
        if list(dictList[index].keys()) == ['pass']:
            tempDict.update(dictList[index])
            failpassList.append(tempDict)
            tempDict = {}
            checkNext = 0


    #If the key is `['fail', 'pass']`, then it is correctly 
    #structured, I can append it to `failpassList`.

    elif list(dictList[index].keys()) == ['fail', 'pass']:

        failpassList.append(dictList[index])

    #If the key is `fail` alone, then wait for the next `pass`.
    #I have done this by incrementing a variable called `checkNext`

    elif list(dictList[index].keys()) == ['fail']:

        checkNext += 1
        tempDict = dictList[index]

    #If the key is `qty` put it in a separate list
    else:
        qtyList.append(dictList[index])

由于qtyListfailpassList的长度相同,  我遍历其中之一,并相应地更新字典。

for i in range(0, len(qtyList)):

    qtyList[i].update(failpassList[i])

print(qtyList)

将产生:

[{'qty': 12, 'fail': 0, 'pass': 12}, {'qty': 12, 'fail': 0, 'pass': 12}, 
{'qty': 12, 'fail': 1, 'pass': 11}, {'qty': 12, 'fail': 1, 'pass': 11}, 
{'qty': 12, 'fail': 1, 'pass': 11}, {'qty': 12, 'fail': 2, 'pass': 10}]

答案 3 :(得分:0)

因此,任务是在保持给定顺序的同时加入字典。

假设某些结构如下:

query_output = [{'qty': 12}, {'qty': 12}, {'qty': 12}, {'qty': 12}, 
    {'qty': 12}, {'qty': 12}, {'fail': 0, 'pass': 12}, {'fail': 0, 'pass': 12},
    {'fail': 1}, {'pass': 11}, {'fail': 1}, {'pass': 11}, {'fail': 1}, 
    {'pass': 11}, {'fail': 2}, {'pass': 10}]

我会做的:

groups = {'qty': [], 'fail': [], 'pass': []}
for d in query_output:
    for k, v in d.items():
        groups[k].append(v)
queries = zip(groups['qty'], groups['fail'], groups['pass'])
result = [{'qty': x, 'fail': y, 'pass': z} for x, y, z in queries]