I have code similar to this. Thing is, I have a dictionary containing key, value pairs obtained from some data processing. BUT sometimes the obtained key is empty, and a placeholder has to be created for each value with an empty key, consisting on a prefix and a numeric suffix.
No, I can't use an array because all the data has to be stored on the dictionary, and 99% of the time there will be proper keys, it's just that sometimes a key cannot be retrieved and since it cannot be empty a name has to be generated.
index = 0
keyname_pattern = '[prefix_{0:02d}]'
while keyname_pattern.format(index) in some_dictionary:
index = 1
self.current_key = keyname.format(index)
# They value is stored in the dictionary at other point in the code.
Thing is, this works perfectly, but for me looks… unpythonic, I can't explain why.
Can this be written in a more compact, explicit, pythonic or just better way?
Thanks a lot!
CodePudding user response:
You could use a control value in the dictionary that contains the next value to be used when creating a "special" key.
For example:
some_dictionary = {}
CONTROL_KEY = '__CONTROL__'
def make_placeholder(dict_):
dict_[CONTROL_KEY] = dict_.get(CONTROL_KEY, -1) 1
return f'[prefix_{dict_[CONTROL_KEY]:02d}]'
for _ in range(5):
print(make_placeholder(some_dictionary))
In this way you don't have to keep searching for the next possible key. If it's likely to interfere with subsequent processing, you could always delete the control key once the dictionary is fully populated.
Output:
[prefix_00]
[prefix_01]
[prefix_02]
[prefix_03]
[prefix_04]