#### python dict get” to use the default key value.

1.Let’s take an example.

Sixteen decimal to decimal system

Enter the sixteen decimal number of any length and convert it to decimal number. The sixteen binary must start with 0x.As above, since all of them start with 0x, you can remove the first two slices.

For example, 0x1a12, slice to turn around, the two place is 1a12.

Conversion to decimal is 1.16^3 + 1016^2 + 1 * 16^1 + 2 * 16^0

We can get 21a1 by reversing the first two digits of the slice, so that as the number of digits goes up, the corresponding N of the 16N power goes up, which is more natural.

```
import math
while True:
hexdict = {'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
try:
rawdata = raw_input()[2:]
sum = 0
if rawdata:
hexdata = rawdata.upper()[::-1]
length = len(hexdata)
for i in xrange(length):
if hexdata[i] >= '0' and hexdata[i] <= '9':
sum = sum + int(hexdata[i]) * math.pow(16,i)
elif hexdata[i] >= 'A' and hexdata[i] <= 'F':
sum = sum + int(hexdict.get(hexdata[i])) * math.pow(16,i)
print(int(sum))
except:
break
```

It can be seen that 0-9 and A-F may be processed in the sixteen binary number respectively.

Can you cut down a few lines of code and deal with 0-9 and A-F in a unified way?This requires the get method of the dictionary to use the default key value.

```
import math
while True:
hexdict = {'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
try:
rawdata = raw_input()[2:]
sum = 0
if rawdata:
hexdata = rawdata.upper()[::-1]
length = len(hexdata)
for i in xrange(length):
sum = sum+int(hexdict.get(hexdata[i],hexdata[i]))*math.pow(16,i)
print(int(sum))
else:
break
except:
break
```

The dictionary’s get method sets the default key value to the dictionary, and when the specified key does not get the key value, the default key value specified by the parameter is used.

Here, when hexdata [i] has a key value corresponding to the hexdict, that is, when the number is A-F, it can be taken to A-F for calculation.

When hexdata [i] doesn’t have a key value in hexdict, which is 0-9, it uses 0-9 itself as the key value to calculate

This eliminates the need to process 0-9 and A-F separately (the first seems to take less time when testing the time performance of different methods)

### Similar Posts:

- IOS development base conversion
- IOS development base conversion
- (C language) arbitrary decimal digits to sixteen
- (C language) arbitrary decimal digits to sixteen
- Conversion between hexadecimal (binary, octal, decimal and sixteen hexadecimal conversion 1. decimal to binary)
- Conversion between hexadecimal (binary, octal, decimal and sixteen hexadecimal conversion 1. decimal to binary)
- Algorithm – – conversion, octal, sixteen – binary, binary
- D 10-08 shaping
- D 10-08 shaping
- ‘Lqb basic practice decimal to sixteen’