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
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.
CodePudding user response:
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:
{'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]
CodePudding user response:
Here are a couple of different approaches.
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:
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 []
). The index k1 == k
is a boolean which selects index 0 or 1 from ds
.
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
:
d2 = {}
for (k, v1), i, n in zip(d1.items(), index, lens):
v2 = values.copy()
v2[i:i n] = v1
d2[k] = v2