Merge a dictionary with list inside

Asked

Viewed 135 times

0

I have to join two dictionaries with list inside, the problem is pq both have list inside.

Code:

valores = {'valor':[1,2,3], 'valor2':[10,20,30]}
valores2 = {'valor':[4,5,6], 'valor2':[10,20,30]}
unidos = {}

data_atos = {'valor': data_atos['valor'].extend(valores['valor'], 'valor2': data_atos['valor2'].extend(valores['valor2']}

Error:

Syntaxerror: invalid syntax

1 answer

1


Hello, all right?

The syntax error is due to you not closing the parenthesis on extend, you can do so in a generalist way:

valores = {'valor':[1,2,3], 'valor2':[10,20,30]}
valores2 = {'valor':[4,5,6], 'valor2':[10,20,30]}
union = {}

# Aqui vai percorrer as chaves do dicionario valores
for v in valores:
    union[v] = valores[v]
    union[v].extend(valores2[v]) 

print(union)
# {'valor': [1, 2, 3, 4, 5, 6], 'valor2': [10, 20, 30, 10, 20, 30]}

If you want a list without repetitions, you can use the set, see how it would look:

valores = {'valor':[1,2,3], 'valor2':[10,20,30]}
valores2 = {'valor':[4,5,6], 'valor2':[10,20,30]}
union = {}

# Aqui vai percorrer as chaves do dicionario valores
for v in valores:
    union[v] = set(valores[v])
    union[v].update(set(valores2[v]))
    union[v] = list(union[v])

print(union)
# {'valor': [1, 2, 3, 4, 5, 6], 'valor2': [20, 10, 30]}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.