Getting key arguments from prepared string [duplicate] - python

This question already has answers here:
Get keys from template
(7 answers)
Closed 5 years ago.
I have a prepared string, e.g. my_string = 'My name is {name}.'
and I have dictionary of kwargs, such as:
format_kwargs = {
'name': 'John',
...
}
So that I can format the string in this manner: my_string.format(**format_kwargs)
That is all good. The problem is that I want to determine what keys are in the string, so that I do not calculate the kwargs needlessly. That is, I have a set of keywords used in these strings by default, but not all of them are used in all strings. They are basically regular messages shown to user, such as '{name}, you account was successfully created!'.
I want to do something like:
format_kwargs = {}
if 'name' in <my_string.keys>:
format_kwargs['name'] = self.get_user().name
if '...' in <my_string.keys>:
format_kwargs['...'] = some_method_...()
my_string.format(**format_kwargs)
How do I retrieve the keys?
EDIT:
a simple if 'name' in my_string does not work because that would also match something like {parent_name} or 'The name change was not successful.'

Use string.Formatter
from string import Formatter
s = 'Hello {name}. Are you {debil_status}'
keys = [i[1] for i in Formatter().parse(s)]
print keys
>>> ['name', 'debil_status']

Related

Python string format template for selected parameters [duplicate]

This question already has answers here:
partial string formatting
(23 answers)
Closed 7 months ago.
I want to create a string template that only selected parameters gets value in each session.
For example:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much"
s.format(fruits_num=fruits_num, fruit_name='apple')
s.format(fruits_num=fruits_num, fruit_name='orange')
I want to avoid the repeated assignment of fruits_num=fruits_num
In a pseduo code:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much".format(fruits_num=fruits_num)
s.format(fruit_name='apple')
s.format(fruit_name='orange')
I this possible? Thanks.
You can double the { around fruits_name so that it will be literal, which will keep it until the next call to .format().
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {{fruit_name}} very much".format(fruits_num=fruits_num)
print(s.format(fruit_name='apple'))
print(s.format(fruit_name='orange'))

Python String to dict while separator is '=' [duplicate]

This question already has answers here:
Splitting a semicolon-separated string to a dictionary, in Python
(6 answers)
Closed 5 years ago.
Hy i have a list of strings which look like:
atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350', 'Note=Pichia pastoris CBS 7435 mitochondrion%2C complete replicon sequence.', 'date=27-FEB-2015', 'mol_type=genomic DNA', 'organelle=mitochondrion', 'organism=Komagataella pastoris CBS 7435', 'strain=CBS 7435']
Now i want to create a dictionary which should look like:
my_dict = {'ID': 'cbs7435_mt', 'Name':'cbs7435_mt', ...}
Do someone has any advice how i could manage this?
Thanks already!
Simply split it with = and use dict()
my_dict = dict(i.split('=') for i in atr)
Use split() method of string to get Key and value for dictionary item.
Use for loop to iterate on given list input.
Demo:
>>> atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350']>>> result_dict = {}
>>> for item in atr:
... key, value = item.split("=")
... result_dict[key] = value
...
>>> result_dict
{'Dbxref': 'taxon:981350', 'ID': 'cbs7435_mt', 'Name': 'cbs7435_mt'}
>>>

Converting list of variables to strings [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I have a list of commands that I want to iterate over so I've put those commands into a list. However, I want to also use that list as strings to name some files. How do I convert variable names to strings?
itemIDScore = """SELECT * from anytime;"""
queryList = [itemIDScore, accountScore, itemWithIssue, itemsPerService]
for x in queryList:
fileName = x+".txt"
cur.execute(x) #This should execute the SQL command
print fileName #This should return "itemIDScore.txt"
I want fileName to be "itemIDScore.txt" but itemIDScore in queryList is a SQL query that I'll use elsewhere. I need to name files after the name of the query.
Thanks!
I don't think you may get name of the variable as string from the variable object. But instead, you may create the list of string of your variables as:
queryList = ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService']
Then you may access the value of variable from the variable name string using the globals() function as:
for x in queryList:
fileName = "{}.txt".format(x)
data = globals()[x]
cur.execute(data)
As the globals() document say:
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
As far as I know, there is no easy way to do that, but you could simply use a dict with what currently are variable names as keys, e.g.:
queries = {
'itemIDScore': 'sql 1',
'accountScore': 'sql 2',
...
}
for x in queries:
fileName = x + ".txt"
cur.execute(queries[x])
print fileName
This would also preserve your desired semantics without making the code less readable.
I think you would have an easier time storing the names explicitly, then evaluating them to get their values. For example, consider something like:
itemIDScore = "some-long-query-here"
# etc.
queryDict = dict( (name,eval(name)) for name in ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService'] )
for k in queryDict:
fileName = k+".txt"
cur.execute(queryDict[k])
You can use the in-built str() function.
for x in queryList:
fileName = str(x) + ".txt"
cur.execute(x)

Call Dictionary With Randomly Chosen Value as Name - TypeError [duplicate]

This question already has answers here:
Access to value of variable with dynamic name
(3 answers)
Closed 6 years ago.
I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.
def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print found_item
Then, I want to use the variable name 'found_item' to call a dictionary of the same name, eg:
print found_item['key_1']
But I get the error, "TypeError: string indices must be integers, not str"
How would I use a string to call a previously defined dictionary that shares the same name?
You can use a variable via its name as string using exec:
dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
Short answer: I don't think you can.
However, if the dictionary explore_items uses the dicts in questions as its keys, this should work.
ETA to clarify:
explore_items = {{dict1}: a, {dict2}:b, {dict3}:c}
random_key= random.choice(explore_items.keys())

Use a string to call function in Python [duplicate]

This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 9 years ago.
Some days ago I was searching on the net and I found an interesting article about python dictionaries. It was about using the keys in the dictionary to call a function. In that article the author has defined some functions, and then a dictionary with key exactly same as the function name. Then he could get an input parameter from user and call the same method (something like implementing case break)
After that I realised about the same thing but somehow different. I want to know how I can implement this.
If I have a function:
def fullName( name = "noName", family = "noFamily" ):
return name += family
And now if I have a string like this:
myString = "fullName( name = 'Joe', family = 'Brand' )"
Is there a way to execute this query and get a result: JoeBrand
For example something I remember is that we might give a string to exec() statement and it does it for us. But I’m not sure about this special case, and also I do not know the efficient way in Python. And also I will be so grateful to help me how to handle that functions return value, for example in my case how can I print the full name returned by that function?
This does not exactly answer your question, but maybe it helps nevertheless:
As mentioned, eval should be avoided if possible. A better way imo is to use dictionary unpacking. This is also very dynamic and less error prone.
Example:
def fullName(name = "noName", family = "noFamily"):
return name + family
functionList = {'fullName': fullName}
function = 'fullName'
parameters = {'name': 'Foo', 'family': 'Bar'}
print functionList[function](**parameters)
# prints FooBar
parameters = {'name': 'Foo'}
print functionList[function](**parameters)
# prints FoonoFamily
You could use eval():
myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)
Beware though, eval() is considered evil by many people.
I know this question is rather old, but you could do something like this:
argsdict = {'name': 'Joe', 'family': 'Brand'}
globals()['fullName'](**argsdict)
argsdict is a dictionary of argument, globals calls the function using a string, and ** expands the dictionary to a parameter list. Much cleaner than eval. The only trouble lies in splitting up the string. A (very messy) solution:
example = 'fullName(name=\'Joe\',family=\'Brand\')'
# Split at left parenthesis
funcname, argsstr = example.split('(')
# Split the parameters
argsindex = argsstr.split(',')
# Create an empty dictionary
argsdict = dict()
# Remove the closing parenthesis
# Could probably be done better with re...
argsindex[-1] = argsindex[-1].replace(')', '')
for item in argsindex:
# Separate the parameter name and value
argname, argvalue = item.split('=')
# Add it to the dictionary
argsdict.update({argname: argvalue})
# Call our function
globals()[funcname](**argsdict)

Categories