Is there any way to compare all item values in a python dictionary?

Asked

Viewed 707 times

0

Is there any way to compare all item values in a dictionary? For example:

a = {'valor1': 4, 'valor2': 5, 'valor3': 4}
b = {'valor1': 2, 'valor2': 2, 'valor3': 8}

if a['valor1']*2<b['valor1']:
    print(f'\033[31m{b[valor1]}\033[m')
else:
    print(f'{b[valor1]}')

I would like to compare the dictionary values a and b and if a dictionary value b is 2 times higher than the dictionary value the value will be painted red.

PS: I would like to compare a value1 with b value1, a value2 with b value2, and so on.

  • The two dictionaries have exactly the same keys?

  • yes, the only things that change are the values

1 answer

2

Nix,

You can use the method keys from the dictionary to return the keys of the same and based on this perform their comparisons:

a = {'valor1': 4, 'valor2': 5, 'valor3': 4}
b = {'valor1': 2, 'valor2': 2, 'valor3': 8}

for i in a.keys():
  if a[i] < b[i]:
    print(f'A chave {i} em a é menor')
  else:
    print(f'A chave {i} em b é menor')

See online: https://repl.it/repls/IdleEcstaticPackagedsoftware


If you need to validate if the key exists in the dictionary, you can use the in:

a = {'valor1': 4, 'valor2': 5, 'valor3': 4}

print('teste' in a)

See online: https://repl.it/repls/AttractiveSimplisticProspect

With this you would avoid accessing a non-existent key in the dictionary, only in case your dictionaries are not equal.

Browser other questions tagged

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