the_martian
the_martian

Reputation: 634

Replace list element with a dictionary key in a loop

I'm working on a function that coverts an integer to hexidecimal. There's more work to be done with two's compliment and handling negatives but right now I'm just working on getting the core logic to work. Here is what I have:

def intToHexaBin(num):
    num = abs(num)
    symdict={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"}
    rlist=[]
    while(num!=0):
        rlist.append(str(num%16))
        num//=16
    rlist=rlist[::-1]
    for i in rlist:
        if int(i) in symdict:
            print("Not sure how to swap list element for a dict value")

    print(''.join(rlist))


intToHexaBin(4512)

I want the output to look like this for this example:

11A0

I'm trying to use a loop to iterate through rlist and check to see if an element in rlist matches a key in symdict. If it does I want to swap the list element for the dictionary value that it matched. So if say 10 is found in the list, it will be found in the dictionary and that element in the list will be changed to "A" the matching dict value. I don't know where to go from here

Upvotes: 1

Views: 571

Answers (1)

niemmi
niemmi

Reputation: 17263

You could use enumerate to iterate over (index, value) tuples. For each value you could use dict.get to either get value from symdict or use default value passed as a second parameter. Then just assign whatever the get returns to the index in rlist:

def intToHexaBin(num):
    num = abs(num)
    symdict={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"}
    rlist=[]
    while(num!=0):
        rlist.append(num%16)
        num//=16
    rlist=rlist[::-1]
    print(rlist)
    for idx, val in enumerate(rlist):
        rlist[idx] = symdict.get(val, str(val))

    print(''.join(rlist))

Note that I've changed rlist to contain integers instead of strings since the keys in symdict are integers as well.

In case you just want convert int to hexadecimal representation you can use hex builtin:

>>> hex(4512)
'0x11a0' 

Upvotes: 1

Related Questions