So I have two dicts called results and results_2 with different lengths with the following setup: Result is also significantly shorter than the Result_2:
result
{('CMS', 'LNT'): 0.8500276624334894,
('LNT', 'CMS'): 0.8500276624334894,
('LOW', 'HD'): 0.8502400376842035,
('HD', 'LOW'): 0.8502400376842036,
('SWKS', 'QRVO'): 0.8507993847326996,
...
result_2
{('CMS', 'CMS'): 1.0,
('CMS', 'LNT'): 0.7761431649456381,
('CMS', 'LOW'): 0.4476903306386938,
('CMS', 'HD'): 0.35617507290738476,
('CMS', 'SWKS'): 0.04797167063700858,
('CMS', 'QRVO'): -0.08844725271734241,
....
Now I want to find all keys which are in both dict and create a new dict with only the duplicate combinations and their values
The Output should look like this:
result_combined
{('CMS', 'LNT'): 0.8500276624334894,
('CMS', 'LNT'): 0.7761431649456381,
....
I have tried using the following code however I am only getting an empty dict:
dict_sorted_2 = {}
for key_2, result_2 in results_2.items():
for key, result in results.items():
if key_2 == key:
dict_sorted[key_2] = result_2
abcd = dict(sorted(dict_sorted_2.items(), key=lambda item: item[1]))
abcd
Out[24]: {}
EDIT:
This is the code I am using to get the result dicts
results_2 = {}
for ticker1 in data_5d:
for ticker2 in data_5d:
if data_5d[ticker1].size == data_5d[ticker2].size:
corr = np.corrcoef(data_5d[ticker1]['%Percentage'], data_5d[ticker2]['%Percentage'])[0,1]
print(f"Correlation between {ticker1} and {ticker2}: {corr}")
results_2[(ticker1, ticker2)] = corr
CodePudding user response:
Coincidentally, the dict.keys
method returns a set-like object that you can do set-like operations on:
>>> a = {(1, 2): 'a', (3, 4): 'b'}
>>> b = {(3, 4): 'c', (5, 6): 'd'}
>>> a.keys() & b.keys()
{(3, 4)}
From there you can pick the values from whichever dict you like:
>>> {k: a[k] for k in a.keys() & b.keys()}
{(3, 4): 'b'}
{('CMS', 'LNT'): 0.8500276624334894, ('CMS', 'LNT'): 0.7761431649456381,
This makes no sense as expected result, as you can't have the same key twice in a dict. Maybe you want this?
>>> {k: (a[k], b[k]) for k in a.keys() & b.keys()}
{(3, 4): ('b', 'c')}