简体   繁体   English

在有条件的情况下合并所有值

[英]Union of all values on a conditional case

I am interested unpacking the values of dictionary that contains a list of values.我有兴趣解包包含值列表的字典的值。

I need to combined all the values inside the dictionary for each key.我需要为每个键组合字典中的所有值。

d1 = {
    'A': ['col1', 'col2'],
    'B': ['col3', 'col4'],
    'C': ['col5', 'col6']
}

The output I want is我要的output是

d2 = {
    'A': ['col1', 'col2', '0 col3', '0 col4', '0 col5', '0 col6'],
    'B': ['0 col1', '0 col2', 'col3', 'col4', '0 col5', '0 col6'],
    'C' : ['0 col1', '0 col2', '0 col3', '0 col4', 'col5', 'col6']
}

d1 = {'A': ['col1', 'col2'], 'B': ['col3', 'col4'], 'C': ['col5', 'col6']}


c1 = [v for k, v in d1.items()]

d2 = {}

for k, v in d1.items():
    for l in c1:
        if l in v:
            d2[k] = l
        else:
            d2[k] = ','.join(l)

How can I unpack all the values for each key, combine them and a static value needs to be added for values not listed to the key.我如何解压每个键的所有值,将它们组合起来,并且需要为键中未列出的值添加 static 值。

You're definitely on the right track.你绝对是在正确的轨道上。

d1 = {'A': ['col1', 'col2'], 'B': ['col3', 'col4'], 'C': ['col5', 'col6']}
all_values = [v for sublist in d1.values() for v in sublist]
d2 = {}

for key in d1.keys():
    new_values = []
    for v in all_values:
       if v in d1[key]:
          new_values.append(v)
       else:
          new_values.append('0 ' + v)
    d2[key] = new_values

Output: Output:

{'A': ['col1', 'col2', '0 col3', '0 col4', '0 col5', '0 col6'], 'B': ['0 col1', '0 col2', 'col3', 'col4', '0 col5', '0 col6'], 'C': ['0 col1', '0 col2', '0 col3', '0 col4', 'col5', 'col6']}

Shorter version:较短的版本:

d2 = {}

for key in d1.keys():
    d2[key] = [v if v in d1[key] else '0 ' + v for v in all_values]

Here are a couple of different approaches.这里有几种不同的方法。

V1 V1

Make a second dictionary with the prefixed values:使用前缀值创建第二个字典:

d1b = {k: [f'0 {x}' for x in v] for k, v in d1.items()}

Now make a list containing the two dictionaries for easier access:现在制作一个包含两个词典的列表以便于访问:

ds = [d1b, d1]

You can now construct the output thus:您现在可以这样构建 output:

d2 = {k: sum((ds[k1 == k][k1] for k1 in d1), []) for k in d1}

This uses sum to apply the operator + to all your values (notice the start value of [] ).这使用 sum 将运算符+应用于您的所有值(注意[]的起始值)。 The index k1 == k is a boolean which selects index 0 or 1 from ds .索引k1 == k是一个 boolean,它从ds中选择索引 0 或 1。

V2 V2

Construct the sum of all the values:构建所有值的总和:

values = [f'0 {e}' for v in d1.values() for e in v]

Also record the lengths their cumulative sum:同时记录长度它们的累计和:

from itertools import accumulate

lens = [len(v) for v in d1.values()]
index = list(accumulate([0] + lens[:-1]))

Now you can do a selective replacement in values :现在您可以对values进行选择性替换:

d2 = {}
for (k, v1), i, n in zip(d1.items(), index, lens):
   v2 = values.copy()
   v2[i:i + n] = v1
   d2[k] = v2

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

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