0

I'm try sum the specific items from two dictionaries but I get always a empty dict.

d1 = {'primary_key': '01/01/20185511', 'Fecha': '01/01/2018', 'linea': '551', 'Sentido': '1', 'trayecto': '3', 'SA_A_': '0', 'SA_B1': '1', 'SA_B2': '2', 'SA_B3': '3'}

d2 = {'primary_key': '01/01/20185511', 'Fecha': '01/01/2018', 'linea': '551', 'Sentido': '1', 'trayecto': '4', 'SA_A_': '1', 'SA_B1': '1', 'SA_B2': '2', 'SA_B3': '3'}

And result should be

{'SA_A_': '1', 'SA_B1': '2', 'SA_B2': '4', 'SA_B3': '6'}

I'm trying with

{key: int(d1.get(key, 0)) + int(d2.get(key, 0)) for key in set(d1) | set(d2) if key is not 'primary_key' and not 'Fecha' and not 'linea' and not 'Sentido' and not 'trayecto'}

But the output is

{}
Tojra
  • 673
  • 5
  • 20
crossmax
  • 346
  • 3
  • 20

3 Answers3

0

Using dict-comprehension:

print({k2: int(v) + int(v2) for (k,v), (k2,v2) in zip(d1.items(),d2.items()) if k2 in select_list})

Which means:

d1 = {'primary_key': '01/01/20185511', 'Fecha': '01/01/2018', 'linea': '551', 'Sentido': '1', 'trayecto': '3', 'SA_A_': '0', 'SA_B1': '1', '': '2', 'SA_B3': '3'}
d2 = {'primary_key': '01/01/20185511', 'Fecha': '01/01/2018', 'linea': '551', 'Sentido': '1', 'trayecto': '4', 'SA_A_': '1', 'SA_B1': '1', 'SA_B2': '2', 'SA_B3': '3'}
d3 = {}    
select_list = ['SA_A_', 'SA_B1','SA_B2','SA_B3']

for (k,v), (k2,v2) in zip(d1.items(),d2.items()):
    if k2 in select_list:
        d3[k2] = int(v) + int(v2)
print(d3)

OUTPUT:

{'SA_A_': 1, 'SA_B1': 2, 'SA_B2': 4, 'SA_B3': 6}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

You can try this way:

{key: int(d1[key]) + int(d2[key]) for key in [val for val in d1.keys()] if key in ['SA_A_', 'SA_B1', 'SA_B2', 'SA_B3']}

Or you can do it like this:

{key: int(d1[key]) + int(d2[key]) for key in [val for val in d1.keys()] if key[0:2] == 'SA'}

OUTPUT:

{'SA_A_': 1, 'SA_B1': 2, 'SA_B2': 4, 'SA_B3': 6}
Marko Šutija
  • 345
  • 3
  • 9
0

You could use collections.Counter like,

>>> import collections
>>> d1
{'primary_key': '01/01/20185511', 'Fecha': '01/01/2018', 'linea': '551', 'Sentido': '1', 'trayecto': '3', 'SA_A_': '0', 'SA_B1': '1', 'SA_B2': '2', 'SA_B3': '3'}
>>> d2
{'primary_key': '01/01/20185511', 'Fecha': '01/01/2018', 'linea': '551', 'Sentido': '1', 'trayecto': '4', 'SA_A_': '1', 'SA_B1': '1', 'SA_B2': '2', 'SA_B3': '3'}
>>> d1c = {k:int(v) for k,v in d1.items() if k.startswith('SA')}
>>> d2c = {k:int(v) for k,v in d2.items() if k.startswith('SA')}
>>> d1c
{'SA_A_': 0, 'SA_B1': 1, 'SA_B2': 2, 'SA_B3': 3}
>>> d2c
{'SA_A_': 1, 'SA_B1': 1, 'SA_B2': 2, 'SA_B3': 3}
>>> collections.Counter(d1c) + collections.Counter(d2c)
Counter({'SA_B3': 6, 'SA_B2': 4, 'SA_B1': 2, 'SA_A_': 1})
han solo
  • 6,390
  • 1
  • 15
  • 19