I currently have a dictionary of dictionaries in which some of the items are related. The items which are related to one another invariably follow a pattern illustrated here:
{ "item" : { "foo" : "bar", "fizz" : "buzz"},
"itemSuper" : { "boo" : "far", "bizz" : "fuzz"},
"itemDuper" : { "omg" : "wtf", "rofl" : "lmao"}}
As you can see, the keys of all the dictionaries which are related have a substring in common which is equal to the full key of one of the dictionaries. I would like to go through my dictionary-of-dictionaries combining all of the contents of such related groups into single dictionaries whose keys are the substring by which the matching was done. So, the end-goal is to end up with something like this for all of these groups:
{ "item" : { "foo" : "bar", "fizz" : "buzz", "boo" : "far", "bizz" : "fuzz", "omg" : "wtf", "rofl" : "lmao"}}
The substring is always the leading part of the key, but may be arbitrary from group to group. So in addition to the "item", "itemSuper" and "itemDuper"
above, there are "thingy"
, "thingySuper"
, and "thingyDuper"
, along with others of that sort.
There are three possible suffixes for the substring; let's call them Super
, Duper
and Uber
. Any of the groups of items I am interested in can have any or all three of these, but there are no other suffixes that may occur.
I would do it following way:
data = { "item" : { "foo" : "bar", "fizz" : "buzz"},
"itemSuper" : { "boo" : "far", "bizz" : "fuzz"},
"itemDuper" : { "omg" : "wtf", "rofl" : "lmao"}}
for key1 in list(data.keys()):
for key2 in list(data.keys()):
if key1!=key2 and key1 in key2:
data[key1].update(data[key2])
del data[key2]
print(data)
Output:
{'item': {'foo': 'bar', 'fizz': 'buzz', 'boo': 'far', 'bizz': 'fuzz', 'omg': 'wtf', 'rofl': 'lmao'}}
Note that this solution is in-place (it alters data
) and that I use for ... in list(...)
- this is crucial, because otherwise I would not be able to del
inside loop.