0

I am trying to export particular globals to a config file based on a dictionary, but the script keeps exporting partial matches, so if I tried to export a global named "value" it would also export "v", "val" and "a". How to prevent that?

data_to_export = {k: v for k, v in globals().items() if k in fields}
Waise
  • 5
  • 1
  • Might it be that you accidentally made `fields` a string instead of a list? That would gives substring matching. If `fields` is a list, I don't see how you get the described behaviour. – Erik Sep 23 '21 at 08:47

1 Answers1

0

You might be running into a problem very similar to this: Python: globals().items() iterations try to change a dict.

When you perform the for loop comprehension, you're creating two new variables v and k that will then be added to the globals list. Instead, try {k: v for k, v in globals().copy().items() if k in fields}

However, I'm not sure what's going on with a. Can you provide an example of the exact output you're seeing for that one?

PeptideWitch
  • 2,239
  • 14
  • 30
  • Sorry, but this is not the issue I have. My issue is not related to the k and v variables, but any variable of name's which a substring named variable exists. For example, if I use this method to export "ply" I will get both "ply" and "y" exported, if "y" is also present in the code. I would like to only export "ply" in this example. – Waise Sep 16 '21 at 07:48