I have two dictionaries with the same keys, one key value in common and the other different values, as follows:
Colombia = {'stats': [{'value': [{'wins': 3}, {'ties': 1}, {'defeats': 2}], 'team': 'Colombia'}],
'cup': 41}
Brasil = {'stats': [{'value': [{'wins': 3}, {'ties': 2}, {'defeats': 1}], 'team': 'Brasil'}],
'cup': 41}
And I need to get a joint dictionary in the following way:
{'stats': [[{'value': [{'wins': 3}, {'ties': 1}, {'defeats': 2}], 'team': 'Colombia'}],
[{'value': [{'wins': 3}, {'ties': 2}, {'defeats': 1}], 'team': 'Brasil'}]],
'cup': 41}
As you can see, I need to concatenate the two dictionaries so that the key stats
contains the content of said key in both dictionaries, but without changing the key cup
.
I found a code in Stack in English but it concatenates the contents of the two keys, doubling the content of the key cup
and obtaining this:
{'stats': [[{'value': [{'wins': 3}, {'ties': 1}, {'defeats': 2}], 'team': 'Colombia'}],
[{'value': [{'wins': 3}, {'ties': 2}, {'defeats': 1}], 'team': 'Brasil'}]],
'cup': [41, 41]}
thing you should not do, you should not do.
The code in question is this:
for key in (colombia.keys() | brasil.keys()):
if key in colombia: result.setdefault(key, []).append(colombia[key])
if key in brasil: result.setdefault(key, []).append(brasil[key])
Is there a way to just concatenate the key stats
of both dictionaries? Is there a generic form that can be used to concatenate up to more than three dictionaries?
Update:
At the end I got the following code:
c = 0
results = []
for i in range(0, len(cups)):
query = []
for j in range(0, len(countries)):
print('Append data ' + str(c))
query.append(data[c])
print(query[j])
c += 1
print (query)
get_cup = itemgetter("cup")
get_stats = itemgetter("stats")
resultados.append([{"cup": cups[i], "stats": list(q["stats"] for q in qs)} for (cups[i], qs) in groupby(sorted(query, key=get_cup), key=get_cup)])
I do not know if the code is clean. Can you further optimize?