The mystical dictionary

This is a fragment of my code:

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(dict):
    res = "d"
    keys = list(dict)
    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 = dict[i]
        >>>*print(i, type(i), type(i) == dict)*<<<
        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"

bencode_dict({'outter': {'inner': 'hello'}})

It output:

{'inner': 'hello'} <class 'dict'> False
d6:outtere

But will output:

{'inner': 'hello'} <class 'dict'> True
d6:outtere

The problem in print(i, type(i), type(i) == dict):
i is a dictionary, but type(i) == dict output False
Why?

Hi!
It’s because you has overwritten the builtin dict type with your argument in thebencode_dict function :slight_smile:

1 Like

But
print(type(i))
Output:
<class 'dict'>
@Eclips4

Yes, it’s right. However, variable dict is no longer pointing to the dict type.
So, there are two ways to solve this problem:

  1. Rename your parameter in function
  2. Compare the type with the actual type dict: print(type(i) == __builtins__.dict)
    The first option is preferable, while the second one is a bit of a hack :slight_smile:
1 Like

Thank you. @Eclips4

1 Like