[Solved] Merging python dictionary values by conditional referencing


The easiest solution would be to iterate through the intersection of the keys and add the corresponding balance and price as an entry in a new dictionary. The intersection isn’t necessary if you can guarantee that if a key exists in either of balance of price, it will exist in the other. As I cannot assume this from your question, you can use the intersection operation on the key sets to produce the common keys (setA.intersection(setB) or simply setA & setB).

keyset = set(bal) & set(price)

Another problem is that your keys are not common names – the keys within the python dictonary have the suffic “ETH”. If you want to perform the intersection check to only take items that a present in both dictionaries, you will need to make the keys of both dictionaries consistent. Easiest solution is to duplicate one dictionary, fixing the inconsistencies.

c_price = dict()
for key in price:
    c_price[key.replace("ETH", "")] = price[key]

or simply

c_price = { key.replace('ETH', ''): price[key] for key in price.keys() }

Now, with two dictionaries with common keys you can create a dictionary that merges the values for each key into an individual dictionary by iterating through the keyset and setting the values on a new dictionary.

keyset = set(bal) & set(price)
for key in keyset:
    combined[key] = {'bal' : bal[key, 'price' : price[key])}

or simply

combined = { key : {'bal' : bal[key], 'price' : price[key]} for key in keyset }

1

solved Merging python dictionary values by conditional referencing