Format strings and named arguments in python
Then simply If you dont want to exchange the values before you could use Solution 3: Why showing key error In your code %(a[‘x’]) will simply convert key argument to «a[‘x’]» This is equivalent to: You can use format or % suggested by other answers Solution 1: Note that dictionaries are unordered data structures, hence you can’t expect any order in printing the items unless you use their ordered equivalent . You could then reserve space when printing for rows with missing values: This would give you the following output: Solution 3: Check if is in the keys of the sub-dictionaries, and to those items, apply a slightly different string operation than the ones that don’t have that key.
How to use Python’s str.format and pass named arguments where the name are defined by variables?
Parameter1 = 'C10' Parameter2 = 'C20' print(" ".format_map())
str.format accepts <> or a index inside the curly braces to assign the provided values as per the given index in the braces and not
You could just do it like this
parameter1 = 10 parameter2 = 20 formatted_string = "<> <>".format(parameter1, parameter2)
(Also the question lacks information required to answer this question)
Python: Formatting a string using variable names, Python: Formatting a string using variable names placeholders. Using four %s can be confusing, so I prefer using variable names: When root_dir, tag and trunk are defined within the scope of a class, using self.__dict__ works well: But when the variables are local, they are not defined in a dictionary, so I use string …
Named string format arguments in Python
format doesn’t alter the string you call it on; it returns a new string. If you do
my_string = "Hi! My name is . I live in " new_string = my_string.format(name='Xi', state='Xo') print(new_string)
then you should see the expected result.
Python String format() Method, Formatting Strings using Escape Sequences You can use two or more specially designated characters within a string to format a string or perform a command. These characters are called escape sequences. An Escape sequence in Python starts with a backslash (\).
Python string formatting with keyword arguments
Need to create one more dictionary.
>>> a= >>> b="this is a %s" >>> c = >>> print b % c[a['x']] this is a testing
You could do the exchange before inserting into string.
Then simply «mystring %s» % y
If you dont want to exchange the values before you could use
Why showing key error
In your code %(a[‘x’]) will simply convert key argument to «a[‘x’]»
a= b="this is a %(a['x'])s print b % "this is a testing"
You can use format or % suggested by other answers
String formatting — How to use Python’s str.format and, str.format accepts <> or a index inside the curly braces to assign the provided values as per the given index in the braces and not
String formatting in Python with variable number arguments
Note that dictionaries are unordered data structures, hence you can’t expect any order in printing the items unless you use their ordered equivalent collections.OrderedDict() . Nevertheless, you can use a generator expression within str.join() method :
In [4]: for key, value in A.items(): print(','.join(("<>: <>=<>(<>)".format(key, t1,t2,t3) for t1, (t2, t3) in value.items()))) . test1: q0=0.123(0.234),test1: phi0=0.124(0.4325),test1: m=9.42(0.3413) test3: q0=0.343(0.353),test3: phi0=0.2341(0.235),test3: m=0.325(0.325),test3: z0=0.234(0.314) test2: q0=0.343(0.353),test2: phi0=0.2341(0.235)
Also note that since we’re doing the following inline unpacking it may raise a ValueError if number of the items in lists is more/less than two.
for t1, (t2, t3) in value.items()
Therefore, make sure that the number of unpacking variables match with the number of items in list.
As both your tests and parameters are in dictionaries, you could first sort them to ensure a consistent ordering. Simple sorting may not work though as if you had test13 , by default in would appear after test1 . You could use the Python library natsort to help with this.
As each set of parameters could have missing values, a quick search could be used to create a list of all of the cols that are needed. You could then reserve space when printing for rows with missing values:
from natsort import natsorted A = < 'test1':, 'test2':, 'test3':, 'test13': > sorted_tests = natsorted(A.items()) # Ensure test13 is numerical sorted correctly # Create a list of all required cols cols = set() for test, params in sorted_tests: cols.update(params.keys()) cols = sorted(cols) for test, params in sorted_tests: row = [(col, params.get(col, [])) for col in cols] cells = [] for p, values in row: if values: cells.append(''.format('<>=<>(<>)'.format(p, values[0], values[1]))) else: cells.append(''.format('')) print(" : <>".format('<>'.format(test), ''.join(cells)))
This would give you the following output:
test1 : m=9.42(0.3413) phi0=0.124(0.4325) q0=0.123(0.234) test2 : phi0=0.2341(0.235) q0=0.343(0.353) test3 : m=0.325(0.325) phi0=0.2341(0.235) q0=0.343(0.353) z0=0.234(0.314) test13 : q0=0.343(0.353) z0=0.234(0.314)
Check if ‘z0’ is in the keys of the sub-dictionaries, and to those items, apply a slightly different string operation than the ones that don’t have that key. Looks a little dirty but produces your output exactly:
for k,v in A.items(): if 'z0' in v: print (k,":","<>=<>(<>)".format('z0',v['z0'][0],v['z0'][1]), " ".join("<>=<>(<>)".format(e,t[0],t[1]) for e,t in v.items() if 'z0' not in e)) else: print (k,": "," ".join("<>=<>(<>)".format(e,t[0],t[1]) for e,t in v.items()))
test1 : q0=0.123(0.234) phi0=0.124(0.4325) m=9.42(0.3413) test2 : q0=0.343(0.353) phi0=0.2341(0.235) test3 : z0=0.234(0.314) q0=0.343(0.353) phi0=0.2341(0.235) m=0.325(0.325)
Note: If you really need those single quotes around the test s, i.e. ‘test1’ instead of test1 , you can add «‘» to the left and right of k in the two print statements of mine: print («‘»,k,»‘».