Home > Software engineering >  calling a dict object / printing dict keys with value
calling a dict object / printing dict keys with value

Time:11-09

I have a list of dict objects called results in the following format:

{('AAPL', 'AAPL'): 1.0,
 ('AAPL', 'ABBV'): 0.2895481094217945,
 ('AAPL', 'AMZN'): 0.7985187751534586,
 ('AAPL', 'BAC'): 0.5923872592768968,
 ('AAPL', 'BRK-B'): 0.6076448647592143,
 ('AAPL', 'COST'): 0.6723253260025647,
 ('AAPL', 'CVX'): 0.2808264364499576,
 ('AAPL', 'GOOG'): 0.7932767338793895,
......

I want to filter through this result list to find values larger than 0.8 For this purpose I am using the following code:

i = 0

for i in results:
        if results[i] > 0.8:
            print(results[i])
      

This gives me the following output:

1.0
0.8506229861474826
0.9999999999999998
1.0
0.8269262016223845
0.8266345202049308
.......

Now in my output I want to also see the ticker combination from my dict list.

I have tried using:

print(results[ticker][I])

which gives me the error:

IndexError: invalid index to scalar variable.

Also I have tried using:

keys = results.keys()
for loop
print(results[keys[i]][I])

Which gave me the error:

TypeError: 'dict_keys' object is not subscriptable

Using the code results.keys()

gives me the required keys:

dict_keys([('AAPL', 'AAPL'), ('AAPL', 'ABBV'), ('AAPL', 'AMZN'), ('AAPL', 'BAC'), ('AAPL', 'BRK-B'), ('AAPL', 'COST'), ('AAPL', 'CVX') ...

Now my only problem is getting the key combination with the result

CodePudding user response:

You're already iterating over the keys, so just print the key as you're going.

for key in results:
    if results[key] > 0.8:
        print(key, results[key])

Alternatively, and more Pythonically, use results.items() so you don't need to access the dict twice:

for key, result in results.items():
    if result > 0.8:
        print(key, result)
  • Related