|
|
|
|
Reply From: |
sg7 |
There is no Update() method. The function for merging dictionaries has to be written.
When merging , the question which should be answered is:
“What to do if the destination dictionary already has a key which exists in the source?”
Typically, we would override the destination existing value unless the key points to the sub-dictionaries in both dictionaries. In such case we can merge the sub-dictionaries.
Testing dictionaries and the results :
var dest = {1:"a", 2:"b", 7:"e" }
var source = {7:{5:"e", 6:"f"}, 4:{4:"d",8:[1,2,3]}}
# result:
# (1:a), (2:b), (4:(4:d), (8:[1, 2, 3])), (7:(5:e), (6:f))
var dest1 = {1:"a", 2:"b", 7:{5:"e", 6:"f"} }
var source1 = {7:"c", 4:"d"}
# result:
# merge_dict = (1:a), (2:b), (4:d), (7:c)
var dest2 = {1:"a", 2:"b", 7:{5:"e", 6:"f"} }
var source2 = {7:{66:"c", 77:"g"}, 4:"d"}
# result:
# (1:a), (2:b), (4:d), (7:(5:e), (6:f), (66:c), (77:g))
var dest3 = {1:"a", 2:"b", 3:{8:{12:"33", 10:"55"}, 9:"44"}}
var source3 = {4:"d", 3:{11:"abc",14:"abcd"}, 10:"67"}
# result
# (1:a), (10:67), (2:b), (3:(11:abc), (14:abcd), (8:(10:55), (12:33)), (9:44)), (4:d)
static func merge_dict(dest, source):
for key in source: # go via all keys in source
if dest.has(key): # we found matching key in dest
var dest_value = dest[key] # get value
var source_value = source[key] # get value in the source dict
if typeof(dest_value) == TYPE_DICTIONARY:
if typeof(source_value) == TYPE_DICTIONARY:
merge_dict(dest_value, source_value)
else:
dest[key] = source_value # override the dest value
else:
dest[key] = source_value # add to dictionary
else:
dest[key] = source[key] # just add value to the dest
Test
func _ready():
merge_dict(dest, source)
print(dest)
merge_dict(dest1, source1)
print(dest1)
merge_dict(dest2, source2)
print(dest2)
merge_dict(dest3, source3)
print(dest3)