this is a dummy version of what a function returns. I would like to know how to extract
'the.email#addresi.want' and 'Nextstringiwant from:
{'blah': {'blah1': 'the.email#addresi.want', 'blah2': 'Nextstringiwant'}, 'blah3': {'-note-': 'blah4', 'blah5': 'blah6', 'blah7': 'blah#bleble.blah', 'blah8': 'blah9'}}
I honestly don't understand the purpose for {} brackets very well, or how to work with it. I cannot change the function that returns this. Please help me, i'm lost. My gut tells me that I should convert this into a normal list and just get the desired position within that list, but it returns this error.
My code:
brackets = function().split(sep=':')
brackets.to_list()
email=brackets[2]
string=brackets[3]
The error:
brackets = creds.split(sep=':')
AttributeError: 'dict' object has no attribute 'split'
Note:
This is exactly how the function returns the {} list, I only changed the values for simplicity sake.
I would really appreciate
As the error message indicates, split is an attribute/method for a string, not for a dictionary.
Your function returns a Python dictionary.
Given your function is called function, you can access the values like this:
result = function()
email_address = result["blah"]["blah1"] # this will be 'the.email#addresi.want'
next_string = result["blah"]["blah2"] # this will be 'Nextstringiwant'
You can get further information on Python dictionaries on this site:
https://realpython.com/python-dicts/
mydict = {
'blah': {'blah1': 'the.email#addresi.want',
'blah2': 'Nextstringiwant'},
'blah3': {'-note-': 'blah4',
'blah5': 'blah6',
'blah7':
'blah#bleble.blah',
'blah8': 'blah9'}
}
[k_ for k_ in mydict.get("blah", dict()).values()]
Output:
['the.email#addresi.want', 'Nextstringiwant']
{} mean json object in Python.
if that function return is string, you should use Json module of python to convert it to json object and access its properties. For example:
import json
obj = json.loads(str_above)
print (obj.blah.blah1)
print (obj.blah.blah2)
Related
I have a tuple like: t= ({'count': 5L},)
Here i don't want to use for loop but want to get value as 5.Then how can i do it?
I tried with coverting to string then using JSON.
import json
s = str(t)
d = json.loads(s)
I got error:ValueError: No JSON object could be decoded
And winded up with no result.
I want to get the value of count as integer 5 & store in a variable.
Anyone having any idea?
No need to use Json since it is already your tuple is already a Python data structure.
If you know the index of the item in the tuple, and you know the keyname you can access it directly using:
t = ({'count': 5L},)
value = int(t[0]['count'])
Background:
I am reading a python file (.py) that has a number of functions defined and using a regex to get the names of all the functions and store them in a list.
d_fncs = {}
list_fncs = []
with open('/home/path/somefile.py', 'r') as f:
for row in f:
search = re.search(r'def (.*)\(', row)
if search:
list_fncs.append(search.group(1))
The above works fine and as expected returns a list of of the function names as strings. I have another list which I plan to use as a counter.
counter = [str(i) for i in range(1,len(list_fncs)+1)]
Finally, I zip the two lists to get a dictionary where the 'keys' are numbers and the associated 'values' are function names
d_fncs = dict(zip(counter,list_fncs))
The problem:
The intent here is to ask user for an input which would be matched with the key of this dictionary (counter). Once the key is matched, the function associated with it is executed. Something like this happens later in the code:
def option_to_run(check, option_enter_by_user):
if check == 'True':
return (connection(d_fncs[option]))
def connection(fnc):
conn_name = Connect(some args..) #class imported
fnc(conn_name)
In this case, as the values from dict are string, I get the following error:
File "/home/path/filename.py", line 114, in connection
fnc(conn_name)
TypeError: 'str' object is not callable
However, if I manually make a dict and run it then I have no issues and functions work as expected:
d_fncs_expected = {'1': function1, '2': function2, ....}
Right now what I am getting is this:
d_fncs = {'1': 'function1', '2': 'function2', ....}
....what can I do to get the dictionary to work in a way so I can call these functions? I want the values not to be strings but a type:class
Replace
fnc(conn_name)
to
eval(fnc)(conn_name) # or eval(fnc(conn_name))
or
globals()[fnc](conn_name)
For example
def myfn(arg):
print(arg +" is printed")
d = {1: 'myfn'}
fun_name = d[1] # 'myfn'
>>>fun_name("something")
TypeError: 'str' object is not callable
>>>eval(fun_name)("something")
something is printed
>>>globals()[fun_name]("someting")
something is printed
I am trying to convert a piece of python code to R. In python, a dictionary within a dictionary is used. So I am trying to utilise the hash package in R,
Python code:
titles = {
'NAME' :{
'exact':['NAME']
,'partial':[]
}
, 'Dt' :{
'exact':['Dt']
,'partial':[]
}
, 'CC' :{
'exact':[]
,'partial':[]
}
}
And the R code is,
library(hash)
titles = hash(("NAME" = list("exact"=list('NAME'),"partial"=list())),
("Dt" = list("exact"=list('Dt'),"partial"=list())),
("CC" = list("exact"=list(),"partial"=list())))
But when i try use this code with hash environment, I am getting this below error.
Error in as.vector(x, "character") :
cannot coerce type 'closure' to vector of type 'character'
When I try to replace hash with list, its working fine. But, I am using key/value pair(hash package) mainly because I have to play around with inner dictionary, I mean change the inner dictionary values based on the outer dictionary keys. Any idea why I am getting this error or any alternative approach.
Updating below to make the question still more clear.
To explain it further, I am creating it as key/value pairs(hash package) mainly because I am going to use the below logic on the dictionaries which heavily use key/value pairs. I am not sure if this can be easily done in R list without key/value pairs.
another_dict = {}
multiples_dict = {}
adj_title = 'Dt'
for outer_key,outer_value in titles.iteritems():
for exact in outer_value['exact']:
if exact == adj_title:
another_dict[actual_title] = outer_key
multiples_dict[outer_key] = multiples
for partial in inner_dict['partial']:
if partial in adj_title:
another_dict[actual_title] = outer_key
multiples_dict[outer_key] = multiples
Thanks in advance.
you need to get rid of the parens surrounding each of the key/value pairs as in:
library(hash)
titles = hash("NAME" = list("exact"=list('NAME'),"partial"=list()),
"Dt" = list("exact"=list('Dt'),"partial"=list()),
"CC" = list("exact"=list(),"partial"=list()))
When you include the parens hash( (a=b) ), the object (a=b) is being passed as an expression and not a key/value pair
http://www.learnpython.org/Serialization_using_JSON_and_pickle
Here are the instructions:
The aim of this exercise is to print out the JSON string with key-value pair "Me" : 800 added to it.
And below is the starting code, which we should modify.
#Exercise fix this function, so it adds the given name and salary pair to the json it returns
def add_employee(jsonSalaries, name, salary):
# Add your code here
return jsonSalaries
#Test code - shouldn't need to be modified
originalJsonSalaries = '{"Alfred" : 300, "Jane" : 301 }'
newJsonSalaries = add_employee(originalJsonSalaries, "Me", 800)
print(newJsonSalaries)
I'm completely lost. The JSON lesson was brief, at best. The issue I seem to be running in to here is that orginalJsonSalaries is defined as a string (containing all sort of unnecessary symbols like brackets. In fact, I think if the single quotes surrounding its definition were removed, originalJsonSalaries would be a dictionary and this would be a lot easier. But as it stands, how can I append "Me" and 800 to the string and still maintain the dictionary-like formatting?
And yes, I'm very very new to coding. The only other language I know is tcl.
EDIT:
OK, thanks to the answers, I figured out I was being dense and I wrote this code:
import json
#Exercise fix this function, so it adds the given name and salary pair to the json it returns
def add_employee(jsonSalaries, name, salary):
# Add your code here
jsonSalaries = json.loads(jsonSalaries)
jsonSalaries["Me"] = 800
return jsonSalaries
#Test code - shouldn't need to be modified
originalJsonSalaries = '{"Alfred" : 300, "Jane" : 301 }'
newJsonSalaries = add_employee(originalJsonSalaries, "Me", 800)
print(newJsonSalaries)
This does not work. For whatever reason, the original dictionary keys are formatted as unicode (I don't know where that happened), so when I print out the dictionary, the "u" flag is shown:
{u'Jane': 301, 'Me': 800, u'Alfred': 300}
I have tried using dict.pop() to replace the key ( dict("Jane") = dict.pop(u"Jane") ) but that just brings up SyntaxError: can't assign to function call
Is my original solution incorrect, or is this some annoying formatting issue and how to resolve it?
The page you linked to says exactly how to do this:
In order to use the json module, it must first be imported:
import json
[...]
To load JSON back to a data structure, use the "loads" method. This method takes a string and turns it back into the json object datastructure:
print json.loads(json_string)
They gave you a string (jsonSalaries). Use json.loads to turn it into a dictionary.
Your last question is a new question, but... When you print a dictionary like that you are just using the fact that python is nice enough to show you the contents of its variables in a meaningful way. To print the dictionary in your own format, you would want to iterate through the keys and print the key and value:
for k in newJsonSalaries:
print("Employee {0} makes {1}".format(k, newJsonSalaries[k]))
There are other problems in your code....
It is weird to load the JSON inside the add employee function. That should be separate...
Also, in your add_employee() function you are hardwired always to add the same values of Me and 800 instead of using the name and salary variables that are passed in, so that line should be:
jsonSalaries[name] = salary
Use this:
import json
def add_employee(jsonSalaries, name, salary):
# Add your code here
jsonSalaries = json.loads(jsonSalaries)
jsonSalaries[name] = salary
jsonSalaries = json.dumps(jsonSalaries)
return jsonSalaries
#Test code - shouldn't need to be modified
originalJsonSalaries = '{"Alfred" : 300, "Jane" : 301 }'
newJsonSalaries = add_employee(originalJsonSalaries, "Me", 800)
print(newJsonSalaries)
Add this before return jsonSalaries:
jsonSalaries = json.dumps(jsonSalaries)
I am trying to make arguments easier to manage in a script I am putting together, I figured I'd wrap a bunch of related items into a dictionary, and pass the dictionary out of the func. pulling out the objects as I need them.
One of these items is a regEx, and I'm struggling to figure out how to structure things properly so I can make it work.
In my initial code (no dictionary). I am 'hard' coding the regex into the parser:
def TopnTail(self,line):
topRegEx = re.compile(r'(<!--make_database header end-->)')
tailRegEx = re.compile(r'(<!--make_database footer start-->)')
searchdumpTopOfPage = topRegEx.search(line)
searchdumpBottomOfPage = tailRegEx.search(line)
if searchdumpTopOfPage:
self.__useLine=1
if searchdumpBottomOfPage:
self.__useLine=0
if self.__useLine == 1:
self.trimmedLines = self.trimmedLines + line + "\n"
return (self.trimmedLines)
in the 'dictionaried' version I want to set the variables in a setter:
def siteDetails():
baseDict = {'topRegex':'''re.compile(r'(<!--make_database header end-->)')''', 'tailRegex':'''re.compile(r'(<!--make_database footer start-->)')'''}
return baseDict
and get to the compiled regex:
def TopnTail(self,line):
topRegEx = baseDict['topRegex']
tailRegEx = baseDict['tailRegex']
searchdumpTopOfPage = topRegEx.search(line)
searchdumpBottomOfPage = tailRegEx.search(line)
if searchdumpTopOfPage:
self.__useLine=1
if searchdumpBottomOfPage:
self.__useLine=0
if self.__useLine == 1:
self.trimmedLines = self.trimmedLines + line + "\n"
return (self.trimmedLines)
but this throws an error:
line 35, in TopnTail
searchdumpTopOfPage = topRegEx.search(line)
AttributeError: 'str' object has no attribute 'search'
Which I am guessing means that its not actually made the regex object, but is still passing the string.
I appreciate that I am probably breaking about 3 cardinal rules here... but any suggestions about how to make it work would be fantastic... (also, first time playing with both classes and dictionaries... so please go easy if I've really messed up!)
How about this?
baseDict = {
'topRegex': r'(<!--make_database header end-->)'
}
And in your TopnTail method
topRegEx = re.compile(baseDict['topRegex'])
The problem with what you have, is that you're assigning a string to topRegEx that contains '''re.compile(r'(<!--make_database header end-->)')'''. Since str has no method search, you get an error.
It makes sense to still compile your regex, and use the returned object. Splitting the contents of the regex into a dict will help if you ever need to changes the regex pattern, or you want to define it dynamically.