key_value
Enhanced dict class for string-based key-value pairs.
- class confirm.utils.key_value.KeyValueDict(string, kvp_separator=':', entity_separator='\n')
This is a dict class on steroids, as it expands the default dict class by supporting key-value based strings for the initialisation. It will split up the key-value pairs (KVP) by the colon (
:
) and the entities by the newline character (\n
). When the string is initialised, all superfluous spaces will be stripped and all invalid KVPs will stripped.- Parameters:
string (str) – The string
kvp_separator (str) – The key-value pair separator
entity_separator (str) – The entity separator
Hint
A single key value pair can be defined like this:
>>> KeyValueDict('spam:eggs') {'spam': 'eggs'} >>> KeyValueDict('spam: eggs') {'spam': 'eggs'} >>> KeyValueDict(' spam : eggs ') {'spam': 'eggs'}
You can also use multiple key value pairs:
>>> KeyValueDict('spam:eggs\nfoo:bar') {'spam': 'eggs', 'foo': 'bar'} >>> KeyValueDict('spam: eggs\nfoo: bar') {'spam': 'eggs', 'foo': 'bar'} >>> KeyValueDict(' spam : eggs \n foo : bar ') {'spam': 'eggs', 'foo': 'bar'}
If you want a different key-value pair sepeartor than
:
, specify thekvp_separator
parameter:>>> KeyValueDict('spam=eggs', kvp_separator='=') {'spam': 'eggs'} >>> KeyValueDict('spam= eggs', kvp_separator='=') {'spam': 'eggs'} >>> KeyValueDict(' spam = eggs ', kvp_separator='=') {'spam': 'eggs'}
If you want a different entity sepeartor than
\n
, specify theentity_separator
parameter:>>> KeyValueDict('spam:eggs,foo:bar', entity_separator=',') {'spam': 'eggs', 'foo': 'bar'} >>> KeyValueDict('spam: eggs, foo: bar', entity_separator=',') {'spam': 'eggs', 'foo': 'bar'} >>> KeyValueDict(' spam : eggs , foo : bar' , entity_separator=',') {'spam': 'eggs', 'foo': 'bar'}
KeyValueDict
instances also support the conversion to an informal string version:>>> str(KeyValueDict('spam:eggs\nfoo:bar')) 'spam: eggs\nfoo: bar' >>> str(KeyValueDict('spam: eggs\nfoo: bar')) 'spam: eggs\nfoo: bar' >>> str(KeyValueDict(' spam : eggs \n foo : bar ')) 'spam: eggs\nfoo: bar'
The
dict.get()
method still works:>>> KeyValueDict('spam:eggs').get('spam') 'eggs' >>> KeyValueDict('spam:eggs').get('foo', None)
Subscript access to the
dict
also works of course:>>> KeyValueDict('spam:eggs')['spam'] 'eggs' >>> KeyValueDict('spam:eggs')['foo'] Traceback (most recent call last): ... KeyError: 'foo'
Iteration is like in a normal
dict
:>>> for key in KeyValueDict('spam:eggs'): ... key 'spam' >>> for key, value in KeyValueDict('spam:eggs').items(): ... f'Value for {key} is {value}' 'Value for spam is eggs'