I have a list of dictionaries:
[
{
'Tahsin': [
{'January': 1}
]
},
{
'Arabic Language': [
{'September': 1}
]
},
{
'Arabic Language': [
{'August': 2}
]
},
{
'Arabic Language': [
{'August': 2}
]
}
]
I want to merge the values under the same keys and remove duplicates.
I tried this following code:
list_of_unique_dicts = []
for dict_ in student_per_course:
if dict_ not in list_of_unique_dicts:
list_of_unique_dicts.append(dict_)
and I got the result:
[
{
'Tahsin': [
{'January': 1}
]
},
{'Arabic Language': [
{'September': 1}
]
},
{
'Arabic Language': [
{'August': 2}
]
}
]
not perfect result, the values of the month still have duplicates.
Then, I tried this following code:
bar = {
k: [d.get(k) for d in list_of_unique_dicts]
for k in set().union(*list_of_unique_dicts)
}
and got this result:
{
'Tahsin': [
[
{'January': 1}
],
None, None
],
'Arabic Language': [
None,
[
{'September': 1}
],
[
{'August': 2}
]
]
}
Still not the perfect result ^_^.
I also tried using Pandas with following code:
res = pd.DataFrame(list_of_unique_dicts).to_dict(orient='list')
And got this result:
{
'Tahsin': [
[
{'January': 1}
],
nan, nan
],
'Arabic Language': [
nan,
[
{'September': 1}
],
[
{'August': 2}
]
]
}
The above still not the result what I want.
The expected result should be:
[
{
'Tahsin': [
{'January': 1}
]
},
{
'Arabic Language':
[
{'September': 1,
'August': 2
}
]
},
]
where the values from the first result are merged.
So, how to do that..?, any help would be appreciated :)