Using A Python List or String in Dictionary Lookup? - python

Use Case
I am making a factory type script in Python that consumes XML and based on that XML, returns information from a specific factory. I have created a file that I call FactoryMap.json that stores the mapping between the location an item can be found in XML and the appropriate factory.
Issue
The JSON in my mapping file looks like:
{
"path": "['project']['builders']['hudson.tasks.Shell']",
"class": "bin.classes.factories.step.ShellStep"
}
path is where the element can be found in the xml once its converted to a dict.
class is the corresponding path to the factory that can consume that elements information.
In order to do anything with this, I need to descend into the dictionaries structure, which would look like this if I didn't have to draw this information from a file(note the key reference = 'path' from my json'):
configDict={my xml config dict}
for k,v in configDict['project']['builders']['hudson.tasks.Shell'].iteritems():
#call the appropriate factory
The issue is that if I look up the path value as a string or a list, I can not use it in 'iteritems'():
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
for k,v in configDict[path].iteritems():
#call the appropriate factory
This returns a key error stating that I can't use a string as the key value. How can I used a variable as the key for that python dictionary?

You could use eval:
eval( "configDict"+path )

You can use the eval() function to evaluate your path into an actual dict object vs a string. Something like this is what I'm referring to:
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
d = eval("configDict%s" % path)
for k,v in d.iteritems():
#call the appropriate factory

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'),

How to access a dictionary key inside a string

I have an API that expects to receive the data in a string format. The data looks like this:
test = """{"API_name":"getScenario","token":"1112223333","clientId":"1","clientEmail":"yup#nope#gmail.com", "more": "hello"}"""
I am used to accessing the dictionary keys rather easily test[token] but in this case it is all encased in a multi-line string.
How is this supposed to be accessed?
Parse the string and then find access by key
import json
data = json.loads(test)
data['API_name']

Unable to store non-characters text in a dictionary in python

I am trying sentiment analysis where I have data like
source_text-> #LiesbethHBC I have a good feeling actually 🙈 its not that long, it's pretty soon!\nAw you deserve these tickets
then! 💖
result_value-> Sentiment(polarity=0.0, subjectivity=0.0)
I want to store this key value pair in a python dictionary.
I tried creating one as:
dict={}
dict[source_text].append(result_value)
but I get KeyError
Is there a way to store such text(just not characters) in a dictionary?
Your problem has nothing to do with "non-character text" (which doesn't mean anything actually), the only requirement for an object to be usable as a dict key is that it's hashable, and there's absolutely no restriction on what you can use as value.
Your problem quite simply comes from the fact that you're trying to get the value for an inexistant key (that's what KeyError means : the key you ask for does not exist in the dict).
Here :
mydict = {}
at this point, mydict is empty so just any item access will raise a KeyError
then you're doing this:
dict[source_text].append(result_value)
which is basically:
something = mydict[source_text] # get value for key `source_text`
something.append(result_value)
Since your dict is empty, the first line WILL obviously raise a KeyError.
If you want to store one unique result_value for each source_text value then the proper syntax is:
mydict[source_text] = result_value
If you want to store a list of result_value for each source_text value then you have to either explicitely test if the key is set, if not set it with an empty list, then append to this list:
if source_text not in mydict:
mydict[source_text] = []
mydict[source_text].append(result_value)
or just use a DefaultDict instead:
from collections import DefaultDict
mydict = DefaultDict(list)
# DefaultDict will automagically create the key with an empty list
# as value if the key is missing
mydict[source_text].append(result_value)
Now I strongly suggest that you invest some time in properly learning Python (hint: there's a quite decent tutorial in the official documentation) if you have to use it, this will save on everyone's time.
The problem is that when you tried to pull out the key #LiesbethHBC I have a good feeling actually 🙈 its not that long, it's pretty soon!\nAw you deserve these tickets then! 💖 in the dictionary which in this case is non-existent, Python gave you a KeyError meaning that the key didn't exist in the dictionary. A simple way to solve this is by initially checking whether you have that particular key in the dictionary, if yes, do whatever you wanna do with it, else create that key first.
By the way, avoid using dict (dictionary datatype) or any other datatypes as a variable name.
This is what you should actually do:
dictionary = {} # Since, 'dict' is the dictionary data-type in Python
if (source_text in dictionary):
# If the key exists...
dictionary[source_text].append(result_value)
else:
# If the key does not exist...
dictionary[source_text] = []
This should help...
Have you tried using '.update' method?
dict = {}
dict.update({'First':'Test'})
dict.update({'Lets Get':'Real'})
print (dict)
Output:
{'Testing': 'Dictionaries', 'Lets Get': 'Real'}
EDIT:
Or even:
dict = {}
dict.update({'Polarity':0.91})
dict.update({'Subjectivity':0.73})
print (dict)
Output:
{'Polarity': 0.8, 'Subjectivity': 0.73}

Retrieve JSON key and value

I am POSTing a .json object to my server with different keys attached.
ID, time, content
On my server I want to then wrap this again in another .json file with another APIs key and value formatting.
So... I want to store the key and value for 'content'
Currently i can obtain the value for 'content by:
content = json_obj['content']
But this only returns the value. What is the syntax for storing the key and value in content? The desirable outcome:
content = {'content' : "........."}
Your JSON_obj here is acting as a dictionary, so you can use Python's items (Python 3+) or iteritems (Python 2.7) functions:
for k,v in json_obj.iteritems():
foo = {k: v}
# do something with foo
Solved, thanks SuperSaiyan you triggered this thought.
Just create a new dictionary:
content = json_obj['content']
test_obj = {'content':content}
Could also:
test_obj = {'content':json_obj['content']}

Does Python 2.6 have a built in URL parameters parser?

Given a URl, how can I get a dictionary of parameters back?
http://docs.python.org/library/urlparse.html
edit: It returns a tuple of the url parameters. If you absolutely need to have it be in a dictionnary looks like you will have to implement it yourself. (get the tuple then assign it to dict)
string = "addressing scheme network location path query fragment_identifier".split()
url = urlparse.urlsplit("url")
dictionary = dict(zip(string,url))
Not sure if that dictionary line is valid, but it's something like that.
ofcourse, it is called urlparse. However, instead of a dictionary, the urlsplit and urlparse methods output a namedtuple object, which you are easily reference by member attributes. If dictionary is a must, you can construct one using those named tuple values too.
And if you want to parse the query params, use parse_qs and parse_qsl from the same module

Categories

Resources