2 days ago i started coding a converter String to HEX. Now i have that code
HEXV = {"A":"41","a":"","B":"42","b":"","C":"43","c":"","D":"44","d":"","E":"45","e":"","F":"46","f":"","G":"47","g":"","H":"48","h":"","I":"49","i":"","J":"","j":"","K":"","k":"","L":"","l":"","M":"","m":"","N":"","n":"","O":"","o":"","P":"","p":"","Q":"","q":"","R":"","r":"","S":"","s":"","T":"","t":"","U":"","u":"","V":"","v":"","W":"","w":"","X":"","x":"","Y":"","y":"","Z":"","z":""}
CHAR = []
def loop():
n = 0
if CHAR[n] in HEXV:
print(HEXV.get(CHAR[n]))
n = 1
i = input(str('Insert Phrase:'))
l = list(i)
CHAR.append(l)
loop()
with that error
C:\Users\Pc\AppData\Local\Programs\Python\Python39>C:/Users/Pc/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/Pc/AppData/Local/Programs/Python/Python39/codes/HEXCODE Converter.py"
Insert Phrase:A
Traceback (most recent call last):
File "c:\Users\Pc\AppData\Local\Programs\Python\Python39\codes\HEXCODE Converter.py", line 16, in <module>
loop()
File "c:\Users\Pc\AppData\Local\Programs\Python\Python39\codes\HEXCODE Converter.py", line 7, in loop
if CHAR[n] in HEXV:
TypeError: unhashable type: 'list'
whetever i change the code it don't solve. i already browsed it but i couldn't solve it and if you would help me I would be grateful
CodePudding user response:
input
returns a string
> i = input('Insert Phrase:')
> Insert Phrase:A
> i
'A'
You made that a list
> l = list(i)
> l
['A']
Then appended that to a list CHAR
> CHAR = []
> CHAR.append(l)
> CHAR
[['A']]
So in your function loop
(which doesn't actually loop btw) you access the nth value which will always be 0 because you're not looping:
> n = 0
> CHAR[n]
['A']
And list's are not hashable so
> CHAR[n] in HEXV
# which is actually this
> ['A'] in HEXV
Gives you the error.
What you could do is use CHAR.extend(l)
instead of CHAR.append(l)
or just pass the actual list to loop. But you need to re-evaluate your code in general because I don't believe this will do what you're actually trying to do.
CodePudding user response:
I'll answer in a way that will hopefully help you to identify the specific error you have asked about, taking your code sample at face value and not commenting on its overall logic or design (since that's not the main point of your question, I have not focused on it).
CHAR
is a list containing another list (l
) and HEXV
is a dict. The Python list data type is indeed not hashable (see the Python docs for dict here and for hashable here), and furthermore, each key in HEXV
is a string of length 1, not a list. Consider using just the first character of CHAR[n]
when checking for presence in HEXV:
if CHAR[n][0] in HEXV: