I have the following code in a python 2.7.10 script
params = {'F': '250', 'I': '-22.5', 'J': '-22.5', 'Y': '12.817175976', 'X': '7.4', 'Z': '-50'}
G3 = 'G3 F {F} I {I} J {J} X {X} Y {Y} Z {Z} \n'
print(params)
print(G3)
print(G3.format(params))
When I try to run it it gives the following output:
./g-codeGenerator.py
{'F': '250', 'I': '-22.5', 'J': '-22.5', 'Y': '12.817175976', 'X': '7.4', 'Z': '-50'}
G3 F {F} I {I} J {J} X {X} Y {Y} Z {Z}
Traceback (most recent call last):
**Traceback truncated**
File "./g-codeGenerator.py", line 342, in siliconOutputSequence
print(G3.format(params))
KeyError: 'F'
Why is this causing the key error, as far as I can see all of the required elements are present in the parameters?
You just need to unpack the dictionary into the format string using the **
operator:
print(G3.format(**params))
Output
G3 F 250 I -22.5 J -22.5 X 7.4 Y 12.817175976 Z -50
It's because .format()
is not expecting a dictionary; it's expecting keyword arguments. .format({'F': 4})
should be changed to .format(F=4)
. To do that with your dictionary, use **
:
print(G3.format(**params))
For more information on argument unpacking, see the docs .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.