Handle duplicate keys and preserve order with VDFDict
masterStandard Python dictionaries cannot represent VDF files that contain duplicate keys. To handle duplicates and preserve insertion order, use vdf.VDFDict as the mapper argument in loading functions.
VDFDict features:
- Duplicate Support: Assigning a value to an existing key creates a duplicate instead of overwriting. Access duplicates using a tuple index:
d[(index, 'key')]. - Order Preservation: Remembers insertion order.
- Key Constraints: Keys must be of type
str. - Special Methods:
get_all_for(key): Returns a list of all values associated with that key.remove_all_for(key): Removes all instances of the specified key.has_duplicates(): ReturnsTrueif the dictionary contains duplicate keys.
import vdf
import collections
# Using VDFDict to handle duplicates and order
d = vdf.loads(vdf_string, mapper=vdf.VDFDict)
# Example of VDFDict behavior
d = vdf.VDFDict()
d['key'] = 111
d['key'] = 222
print(d.items()) # [('key', 111), ('key', 222)]
print(d['key']) # 111 (returns the first occurrence)
print(d[(1, 'key')]) # 222 (accesses the second duplicate)
print(d.get_all_for('key')) # [111, 222]
d.remove_all_for('key')
print(len(d)) # 0