'Maximum recursion depth exceeded' error

The part of the code must encode the dictionary using Bencode.

def sort_dict(MyDict):
    myKeys = list(myDict.keys())
    myKeys.sort()
    return {i: myDict[i] for i in myKeys}

def bencode_list(list):
    res = "l"
    for i in list:
        if type(i) == int:
            res += "i" + str(i) + "e"
        elif type(i) == str:
            res += str(len(i)) + ":" + i
    return res + "e"

def bencode_dict(dicts):
    res = "d"
    dicts = sort_dict(dicts)
    keys = list(dicts)
    for i in keys:
        if type(i) == int:
            res += "i" + str(i) + "e"
        elif type(i) == str:
            res += str(len(i)) + ":" + i
        elif type(i) == list:
            res += bencode_list(i)
        elif type(i) == dict:
            res += "d" + bencode_list(i)
        i = dicts[i]
        if type(i) == int:
            res += "i" + str(i) + "e"
        elif type(i) == str:
            res += str(len(i)) + ":" + i
        elif type(i) == list:
            res += bencode_list(i)
        elif type(i) == dict:
            res += bencode_dict(i)
    return res + "e"

print(bencode_dict({'t': 'aa', 'y': 'q', 'q': 'ping', 'a': {'id': '01234567890897653412'}}))

It will output:

d1:ad2:id20:01234567890897653412e1:q4:ping1:t2:aa1:y1:qe

But error occurs:

---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-54-bfdb4b6d3071> in <cell line: 66>()
---> 66 print(bencode_dict({'t': 'aa', 'y': 'q', 'q': 'ping', 'a': {'id': '01234567890897653412'}}))


1 frames
... last 1 frames repeated, from the frame below ...

<ipython-input-54-bfdb4b6d3071> in bencode_dict(dicts)
     34             res += bencode_list(i)
     35         elif type(i) == dict:
---> 36             res += bencode_dict(i)
     37     return res + "e"
     38 

RecursionError: maximum recursion depth exceeded while calling a Python object

Why? How can I fix this?

This might be a bit of a problem here. Either that, or it’s a copy/paste error.

Thanks, I found an alternative way.