Concatenate two dictionaries without repeating field

1

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?

    
asked by SalahAdDin 17.05.2016 в 00:46
source

1 answer

5

Limiting myself to answer your question: dictionaries are not concatenated . What you really want to do is concatenate the lists that the dictionaries have in their key stats . More or less like this:

# cada pais es un diccionario con una clave "stats"
paises = [colombia, brasil, ecuador, peru]

resultado = { "cup":41,
              "stats": [pais["stats"] for pais in paises] }

Edited : consider groupings by the key cup

If you want to put the dictionaries together with the same value of the key cup :

# cada pais es un diccionario con una clave "stats"
paises = [colombia, brasil, ecuador, peru]

# set de todas las "cups"
cups = set(pais["cup"] for pais in paises)

resultado = [{ "cup": cup,
               "stats": [pais["stats"] for pais in paises
                                       if pais["cup"] == cup }
               for cup in cups ]

Another more complicated method, but which I personally prefer if there are many dictionaries to be processed:

from operator import itemgetter
from itertools import groupby

paises = [colombia, brasil, ecuador, peru]
get_cup = itemgetter("cup")
get_stats = itemgetter("stats")
resultados = [
   { "cup": cup,
     "stats": list(p["stats"] for p in ps) }
  for (cup, ps) in groupby(sorted(paises, key=get_cup), key=get_cup) ]

Variation : Suppose we want a dictionary, having in each item the statistics of each cup:

from operator import itemgetter
from itertools import groupby

paises = [colombia, brasil, ecuador, peru]
get_cup = itemgetter("cup")
get_stats = itemgetter("stats")
resultados = {
  cup: list(p["stats"] for p in ps) 
  for (cup, ps) in groupby(sorted(paises, key=get_cup), key=get_cup) }
    
answered by 17.05.2016 / 10:04
source