-3

There are two dictionaries (d1 and d2) formed after combining list values. I have to subtract the values (d2-d1) and print the dictionary.

d1 = {'Rash': '80000000', 'Kil': '80000020', 'Varsha': '80000020', 'sam': '80010000'}  
d2 = {'Varsha': '8000ffe0', 'sam': '80014000', 'Kil': '8000ffe0', 'Rash': '801fffff'}  

d3 = {key: d2[key] - d1.get(key, 0) for key in d2}  
print(d3)

This is not working as it is giving type error:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Yash K
  • 17
  • 4
  • 4
    Does this answer your question? [Convert hex string to int in Python](https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python) and [Python integer to hex string with padding](https://stackoverflow.com/questions/40123901/python-integer-to-hex-string-with-padding) – trincot Aug 18 '20 at 09:37

1 Answers1

1

Convert those string values to int (with base 16), find the difference and convert it back to hex

>>> d3 = {key: f"{int(d2[key], 16) - int(d1.get(key, '0'), 16):x}" for key in d2}  
>>> d3
{'Varsha': 'ffc0', 'sam': '4000', 'Kil': 'ffc0', 'Rash': '1fffff'}
Prem Anand
  • 2,469
  • 16
  • 16
  • 2
    To convert back to the same format as the OP, don't use `hex`, use `f"{int(d2[key], 16) - int(d1.get(key, 0), 16):x}"`. Also, I think the default value should be `'0'` not `0` – juanpa.arrivillaga Aug 18 '20 at 09:40