I am trying to get the value from a dictionary with a filepath as the key and a number as the value. I am trying to get the value using the dict[key] method and when I configure the variable as either single backslash or double backslash I still get a KeyError when the variables look the same:
from pathlib import Path
print(job_slurm_dict)
print(Path(f'{site_dir}/hfoutp.in'))
try:
print(job_slurm_dict[Path(f'{site_dir}/hfoutp.in')])
except KeyError:
print('KEYERROR 1')
try:
print('\\\\'.join(f'{site_dir}\hfoutp.in'.split('\\')))
print(job_slurm_dict['\\\\'.join(f'{site_dir}\hfoutp.in'.split('\\'))])
except KeyError:
print('KEYERROR 2')
sys.exit(1)
I get the following output:
{'7ded3d66-8ed6-4edc-9127-b6ba2a598369\\reagent\\hfoutp.in': '17312073_1', '7ded3d66-8ed6-4edc-9127-b6ba2a598369\\3\\hfoutp.in': '17312073_2', '7ded3d66-8ed6-4edc-9127-b6ba2a598369\\4\\hfoutp.in': '17312073_3', '7ded3d66-8ed6-4edc-9127-b6ba2a598369\\6\\hfoutp.in': '17312073_4'}
7ded3d66-8ed6-4edc-9127-b6ba2a598369\3\hfoutp.in
KEYERROR 1
7ded3d66-8ed6-4edc-9127-b6ba2a598369\\3\\hfoutp.in
KEYERROR 2
When I try to print each key from the dictionary it looks like this: 7ded3d66-8ed6-4edc-9127-b6ba2a598369\3\hfoutp.in
.
I am not sure why I am getting a KeyError when using this variable in either form to access the value from the dictionary since both the key and the variable are exactly the same.
Many thanks in advance.
CodePudding user response:
The problem is that you are trying to print and access the dictionary with different data types.
In the first instance you are accessing the dictionary using a Path and in the second instance using a string. The reason it looks like the same key is because dictionary and Path converts differently to string. A string in a dictionary prints with double \\, while if you print the string directly it will just be one \.
If you convert the Path to string first, i.e., str(Path(...))
, then it should work.