Reputation: 3889
I have a dict like this:
{'d': {'BidVolume1': 0, 'BidPrice1': 0.0, 'BidVolume2': 0, 'BidPrice2': 0.0, 'BidVolume3': 0, 'BidPrice3': 0.0, 'BidVolume4': 0, 'BidPrice4': 0.0, 'BidVolume5': 0, 'BidPrice5': 0.0, 'AskTotalVolume': 0}}
When I try this code
for key in r['d'].items() :
print(key['BidTotalVolume'])
I get the following error message:
TypeError: tuple indices must be integers or slices, not str
What I am trying to do is to say to the program, give me the value of the item with the BidTotalVolume
key.
How should I do that? Why do I get this error message?
Upvotes: 1
Views: 7605
Reputation: 140196
r[d]
is {'BidVolume1': 0, 'BidPrice1': 0.0, 'BidVolume2': 0, 'BidPrice2': 0.0, 'BidVolume3': 0, 'BidPrice3': 0.0, 'BidVolume4': 0, 'BidPrice4': 0.0, 'BidVolume5': 0, 'BidPrice5': 0.0, 'AskTotalVolume': 0}
so it's a dictionary.
Now you're iterating on a dictionary like this:
for key in r['d'].items()
the key
name is misleading. Here key
is a tuple
of keys & values. When trying to use []
on that tuple you get that error. You should access your data directly like this:
print(r['d']['BidTotalVolume'])
Upvotes: 1
Reputation: 683
As suggested in the comment, use
for key, values in d.items():
as items () returns a tuple of (key, value). For only keys, you can use keys() and for only values , you can use values()
Upvotes: 0
Reputation: 16147
First, there doesn't appear to be a bidtotalvolume key in your dictionary.
Secondly what you're attempting to do here is more or less:
print(r['d'][key]['BidTotalVolume'])
You don't have 3 levels to your dictionary so that's never going to work.
I assume what you mean to do is:
for key, value in r.items():
print(r[key]['BidTotalVolume'])
Which will fail because BidTotalVolume is not in your dictionary. But try it with any key that is in there and it should work.
Upvotes: 1