Add values between ICT

Asked

Viewed 536 times

3

GOAL:

I am trying to add the values between Dict ct_db and ct_db2, whenever the keys are equal.

Example:

RR-00 == RR-00, so make 14 + 223

Problem:

It is not being compared all Dict keys, the operation is finished as soon as it is covered once the Dict, but since the keys are out of order, the correct calculations are not made

SCRIPT:

ct_db = {u'AB-00': 18, u'RR-00': 14, u'LD-00': 56, u'SR-00': 33, u'YT-00': 452}
ct_db2 = {u'CD-07': 26, u'RR-00': 223, u'LD-00': 367, u'SR-00': 257, u'IA-00': 11}

not_installed = []
for elemA, elemB in zip(ct_db, ct_db2):
        if(elemA == elemB):
                print("MATCH "+elemA+" - "+elemB)
                not_installed.append(ct_db[elemA] + ct_db2[elemB])
        else:
                print("NOT MATCH "+elemA+" - "+elemB)

print(not_installed)

OUTPUT:

NOT MATCH LD-00 - CD-07
NOT MATCH SR-00 - LD-00
NOT MATCH AB-00 - RR-00
NOT MATCH RR-00 - IA-00
NOT MATCH YT-00 - SR-00
[]

2 answers

4

Seems like a good use for collections.Counter:

from collections import Counter

ct_db = {u'AB-00': 18, u'RR-00': 14, u'LD-00': 56, u'SR-00': 33, u'YT-00': 452}
ct_db2 = {u'CD-07': 26, u'RR-00': 223, u'LD-00': 367, u'SR-00': 257, u'IA-00': 11}

soma = Counter(ct_db) + Counter(ct_db2)
print(soma)
# Counter({'YT-00': 452, 'LD-00': 423, 'SR-00': 290, 'RR-00': 237, 'CD-07': 26, 'AB-00': 18, 'IA-00': 11})

# Também podemos obter um dicionário novamente
print(dict(soma))
# {'AB-00': 18, 'RR-00': 237, 'LD-00': 423, 'SR-00': 290, 'YT-00': 452, 'CD-07': 26, 'IA-00': 11}

3


In the above code, Voce always compares the values of the same Dict index.. And if you ever do anything like that?:

ct_db = {u'AB-00': 18, u'RR-00': 14, u'LD-00': 56, u'SR-00': 33, u'YT-00': 452}
ct_db2 = {u'CD-07': 26, u'RR-00': 223, u'LD-00': 367, u'SR-00': 257, u'IA-00': 11}

not_installed = []
for elemA in ct_db:
    if elemA in ct_db2:
        print("MATCH "+elemA)
        not_installed.append(ct_db[elemA] + ct_db2[elemA])
    else:
        print("NOT MATCH "+elemA)

print(not_installed)

It may not be the most optimized way, but I think it solves

  • But already help friend, thank you so much for sharing your knowledge!

  • I made some adjustments to the code, take a look later. It got a little simpler

  • thank you very much!

Browser other questions tagged

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