I am working on a little Python method that needs to read a dictionary from another file that will represent the key and values.
But it seems I am running into a problem with the representation of the number values that I am sending over. For example, some keys in my dictionary would look like this:
id_dict = {
'val_a': 0x0000,
'val_b': 0x1000
}
But I noticed that when I attempt to iterate through the dictionary, the hexadecimal is replaced with the decimal value. Even in the original id_dict.py
, where the dictionary is located, the numbers are converted from hex automatically.
This is my result of trying to iterate through it:
for k,v in id_dict.items():
print(k,v)
#Results
val_a 0
val_b 4096
Can someone tell me why the values are being represented in decimal form and not in the hexadecimal form that they are originally stored in?
And if there is a way to stop the automatic conversion, that would be great to understand as well!
Can someone tell me why the values are being represented in decimal form and not in the hexadecimal form that they are originally stored in?
They were not originally stored in hexadecimal. Python does not track any information about base; whether you type 0x1000
or 4096
in your source code, it's the same number, and Python stores it the same way.
When Python prints a number, it has to choose a base to display it in, and the default is always decimal. If you want to print it differently, you will need to specify a different way to perform string conversion, such as the hex
function:
>>> print 0x1000
4096
>>> print hex(0x1000)
0x1000
Python stores the numbers the same way, the only thing that changes is the formatting. Your issue is how the numbers are being formatted, not represented, thus, you fix your problem with string formatting:
>>> d = {k:v for k,v in zip('abcdefg',range(1,5000,313))}
>>> d
{'e': 1253, 'g': 1879, 'a': 1, 'd': 940, 'c': 627, 'b': 314, 'f': 1566}
>>> for k,v in d.items():
... print("{} {:#06x}".format(k,v))
...
e 0x04e5
g 0x0757
a 0x0001
d 0x03ac
c 0x0273
b 0x013a
f 0x061e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With