3

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

facepalm Thanks, I feel like a real idiot now looking about 4 lines above my code snippet and seeing exactly that where it's working properly.
Don't worry. It took me a minute to see your problem ;)
4

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.