Python KeyError with Windows filepath as key - python

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.

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.

Related

root.find() not working when called from dictionary- element tree

Im currently using the module element tree & urllib to access/parse and return values from xml files.
Using the root.find/root.findall() methods along with XPath syntax to locate desired info in xml. Then using (.text) to return the value of child/grandchild elements.
When assigning each root.find() to a variable then taking the variable and attaching (.text), i am able to parse and return the value with no issues.
(i.e)
x= root.find(./Cameras/Camera/Connected')
print (x.text)
==> True
However I would like to place these "root.find()" in a dictionary and call on them later in the script.
(i.e)
location= {
'Cam': "root.find('./Cameras/Camera/Connected')",
'Mic': "root.findall('./Audio/Input/Connectors/Microphone')",
'Prod_ID': "root.find('./SystemUnit/ProductPlatform')"
}
However, when indexing to dictionary by key and then attempting the add the (.text) i get the following error;
y=location['Cam']
print (y.text)
==> AttributeError: 'str' object has no attribute 'text'
So this maybe a simple issue im overlooking but do these two methods return the same value? Can the element tree module read root.find() from dictionaries?
You're setting your dictionary values to a literal string. That is, this:
'Cam': "root.find('./Cameras/Camera/Connected')",
Is setting the value of key Cam to the string value root.find('./Cameras/Camera/Connected'). You want to actually call the function and set the key to the return value, so you need to drop the quotes:
'Cam': root.find('./Cameras/Camera/Connected'),

Use dictionary as lookup table

I have a jinja template that I want to pass a value into (an identifier for a country). The format of the data is a two letter country code (for example "PL" for Poland).
Through the template, I need to pass the corresponding flag as an output, but the flag is saved in the app folder structure, so i need to get the path to the image.
My problem: I could not figure out a way to use os.path in jinja, so now im trying to solve it by creating a dictionary that matches country string and relative path like this:
countries = {"PL" : "countries/flags/poland.png"}
where the system path to the app folder gets added afterwards in Python through os.path.
My question: How can i use the country string I am getting to automate transformation into the path format of the country? Something like:
for data in countries:
if data in countries.keys:
return countries.value
Thanks in advance!
Assuming data is a country code (like "PL" for example):
def get_path(data):
return countries.get(data)
The get() method checks if the dictionary has the key, and if so returns the corresponding value, otherwise it returns None.
If you want a default value other than None when the key is not present you can specify it as second argument, like this:
def get_path(data):
return countries.get(data, "default/path/x/y/z")

Try keys in a dictionary until one works - python 2.7

My dictionary contains keys (which may or may not repeat) and values (which are all unique). I get an exception error when my key, value pair does not work. When I get an exception, I would like to move to the next matching key, and try it's value. If none of them work, reach "finally" exception handler and just continue to next key.
Below is sort of the logic laid out, except my current logic would only try one other key possibility when I would like to exhaust all key options before reaching "finally".
for currentFile, originalFile in filepath_dictionary.items():
try:
relocateSource(currentFile, originalFile)
except:
# (Some logic which tries the next key, value pair in which the key matches the current key
finally:
print 'Could not relocate file: ' + currentFile
If you think that your keys repeat, but your values don't, then you have your data structure wrong, because dictionary keys are unique.
There are two possible solutions:
Reverse your dictionary structure so that the unique filenames are keys and the repeating filenames are the values.
Make each value of your dictionary a list of filenames, so that the several unique filenames are associated with the repeating filename. In other words, you represent the repetition of the repeating filename by associating it with several unique filenames instead of only one.
Taking the second option gives you something like this:
for current_file, original_files in filepath_dictionary.items():
for original_file in original_files:
try:
relocate_source(current_file, original_file)
break
except:
pass
else:
print 'Could not relocate file: ', current_file
In a Python dictionary, all keys are unique.
Maybe you should keep values of repeated keys in a list and simply search in that list if exception raises.
dct = {key1: [val2_k1, val2_k1], key2: [val2_k2]}

Pass a variable to extract from JSON String in Python?

I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]

Getting a keyerror when accessing the list in a dictionary using _getitem_() function

I have a dictionary
title_data = {'1':['City','State','Town']}
and I would like to get the State value so I use title_data['1']._getitem_(1) and I get a keyerror, even though I checked and that key is in the dictionary.
title_data['1'] already gives you the value for '1' in the dictionary: a list. get the second element using title_data['1'][1].
>>> title_data = {'1':['City','State','Town']}
>>> title_data['1'][1]
'State'
It is spelled __getitem__ (double underscore at each side; _getitem_ will give you AttributeError). You will probably never need to use it (that's what the underscore is for), but if you do, it works perfectly:
>>> title_data['1'].__getitem__(1)
'State'
I don't know how did you get the KeyError; maybe you did title_data[1].__getitem__(1) or something like that.
If you execute:
title_data = {'1':['City','State','Town']}
title_data['1']._getitem_(1)
in python 2.7 you get an AttributeError because the list that is returned by title_data['1'] has no method _getitem_.
You are missing the double underscore: __getitem__():
title_data = {'1':['City','State','Town']}
title_data['1'].__getitem__(1)
works, as does of course the more commonly used:
title_data = {'1':['City','State','Town']}
title_data['1'][1]

Categories

Resources