1

Just started learning Python a month ago. I'm stumped on an issue. Trying to update a dictionary using a for loop. I would like to store the variable using the for loop's variable name as key and the variable value as the dictionary's value. I'm trying to use % to make it a one liner. Here's what I have so far:

grbl_parser_d = {
'a': 'null',  # Motion Mode
'b': 'null',  # Coordinate System Select
'c': 'null'  # Plane Select
}

grbl_out = [GC:G0 G54 G17]

def filtergrblparser():
    global grbl_parser_d
    for l, r in [grbl_out.strip('[]').split(':')]:
        for a, b, c in [r.split(' ')]:
            # grbl_parser_d.update({'%': x}) % x
            grbl_parser_d.update({'a': a})
            grbl_parser_d.update({'b': b})
            grbl_parser_d.update({'c': c})

The 'grbl_out' variable is the output from an Arduino.

Trying to use something like: grbl_parser_d.update({'%': a}) % a.name

'a.name' would be the for loop's variable name, not the value. Is this even possible? Any other suggestions and tips to clean up the code would also be greatly appreciated. Thanks!

2 Answers 2

1

You don't need loops for this, and I wouldn't try to cram it onto one line. Here's a simple function that should do what you want.

def filtergrblparser(grbl_out):
    l, r = grbl_out.strip('[]').split(':')
    a, b, c = r.split(' ')
    grbl_parser_d = {
        'a': a,  # Motion Mode
        'b': b,  # Coordinate System Select
        'c': c  # Plane Select
    }
    return grbl_parser_d

# I'm assuming you meant this to be a string
grbl_out = "[GC:G0 G54 G17]"

grbl_parser_d = filtergrblparser(grbl_out)

print(grbl_parser_d)
# {'a': 'G0', 'b': 'G54', 'c': 'G17'}
Sign up to request clarification or add additional context in comments.

Comments

0

This is generally a bad idea, but it could be done with another for loop.

# it's not clear why you're throwing this in a list just to iterate once over it
l, r = grbl_out.strip('[]').split(':')
a, b, c = r.split(' ')
for k in ['a', 'b', 'c']:
    grbl_parser_d[k] = vars()[k]

But really it looks like you're trying to do:

grbl_parser_d = dict(zip('abc', grbl_out.strip('[]').split(':')[1].split(' ')))

Which is probably best written as:

l, r = grbl_out.strip('[]').split(':')
grbl_parser_d = dict(zip('abc', r.split(' ')))

1 Comment

Thank you! grbl_parser_d = dict(zip('abc', grbl_out.strip('[]').split(':')[1].split(' '))) is exactly what I was looking for.

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.