'Append values from one dict to a dict of lists and append None where the keys don't match to keep lists the same length
I have two dicts.
d1 = {
"A": 10,
"C": 30,
}
d2 = {
"A": [1, 5],
"B": [3, 6],
"C": [90, 2],
"D": [7, 22],
}
And I would like to add the values from d1 to the lists in d2. Where the keys from d1 are not in d2, then None is added to the lists at the missing keys in d2. So that all the lists remain the same length. For a result that looks like this:
merged = {
"A": [1, 5, 10],
"B": [3, 6, None],
"C": [90, 2, 30],
"D": [7, 22, None],
}
What is an efficient way to do this?
Solution 1:[1]
d1 = {
"A": 10,
"C": 30,
}
d2 = {
"A": [1, 5],
"B": [3, 6],
"C": [90, 2],
"D": [7, 22],
}
merged = {k: v + [d1.get(k)] for k, v in d2.items()}
print(merged)
# {'A': [1, 5, 10], 'B': [3, 6, None], 'C': [90, 2, 30], 'D': [7, 22, None]}
Solution 2:[2]
If you want to avoid modifying d2, you can create a new dictionary to store your output like so:
merged = {}
for key, value in d2.items():
merged[key] = value + [d1.get(key)]
Solution 3:[3]
Define "efficient". There are two possible answers for the problem.
The first is to use a for loop, like this:
for key in d2.keys():
d2[key].append(d1.get(key))
Explaining: you go through the keys of the bigger dict, then use get to verify if the key exists in d1 and append the value, or None, to d2. The output is d2.
The second solution would be to use pandas' DataFrames, which may be more efficient. The process is simple, turn everything into a DataFrame, then just merge them.
At the top of your code, import the pandas package, or the DataFrame module.
from pandas import DataFrame
Then, after defining your d1 and d2
df1 = DataFrame(d1, index=[0])
df2 = DataFrame(d2)
merged = df2.append(df1)
Explaining: as d1 doesn't contains a list, you need to determine that the only entry in the DataFrame is in index=0, the d2 don't need it, because the list already set their indexes; the columns of the DataFrame will be the keys of the dictionary.
Later you can turn your DataFrame back to a dictionary, but this would render the method unefficient.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Itay Raveh |
| Solution 2 | Cameron Riddell |
| Solution 3 |
