Dictionary with nested list TypeError: string indices must be integers

时间:2019-02-18 00:25:42

标签: python json django dictionary

My json response come back with this dictionary.

data = {"offset": 0, "per-page": 1, "total": 548, "language": "en", 
"odds-type": "DECIMAL", "overall-staked-amount": 23428.63548, 
"profit-and-loss": 4439.61471, "events": [{"id": 1042867904480016, 
"name": "Gael Monfils vs Daniil Medvedev", "sport-id": 9, "sport- 
url": "tennis", "sport-name": "Tennis", "start-time": "2019-02- 
16T14:29:00.000Z", "finished-dead-heat": false, "markets": [{"id": 
1042867905130015, "name": "Moneyline", "commission": 0, "net-win- 
commission": 0, "profit-and-loss": -0.59999, "stake": 0.59999, 
"selections": [{"id": "1042867905220015_BACK", "runner-id": 
1042867905220015, "name": "Daniil Medvedev", "side": "BACK", "odds": 
3.0, "stake": 0.59999, "commission": 0, "profit-and-loss": -0.59999, 
"bets": [{"id": 1043769075060320, "offer-id": 1043764555430020, 
"matched-time": "2019-02-16T16:16:18.936Z", "settled-time": "2019- 
02-16T16:26:01.878Z", "in-play": true, "odds": 3.0, "stake": 
0.59999, "commission": 0, "commission-rate": 2.0, "profit-and-loss": 
-0.59999, "status": "PAID"}]}], "net-win-commission-rate": 0.02}]}]}

I am unable to get the attribute value for overall-staked-amount and inside the events list I cannot get name from events list. using list comprehension or a for loop.

Here's my code.

list comp

overall_staked = [d['overall-staked-amount'] for d in data]

print(overall_staked)

for loop

for d in data:
    overall_staked = d['overall-staked-amount']
    name = d['name']
    print(overall_staked,name)

I receive an error TypeError: string indices must be integers what am I doing wrong or need to do?

3 个答案:

答案 0 :(得分:1)

无需重复,只需执行以下操作:

overall_staked = data['overall-staked-amount']

按照相同的逻辑获取其他数据

答案 1 :(得分:0)

datadictionary,例如:

mydict = {"item_1": 3, "item_2": 5}
for item in mydict:
    print(item)

它将打印字典键:

item_1
item_2

那是字符串,这就是为什么要尝试的原因:

mydict = {"item_1": 3, "item_2": 5}
    for item in mydict:
        # item is a string here, so if you
        # Python complains about string indexes must be integers.
        item['overall-staked-amount']

这是完全相同的理解问题。

您可以通过以下方式获得所需的值:

overall_staked_amount = data['overall-staked-amount']

您可以通过以下方式遍历键和项:

for key, value in data.items():
    # ...

答案 2 :(得分:0)

好吧,当您遍历字典时,您遍历了其键(即字符串)。并且,要访问字符串,您需要一个int值。这就是为什么您会收到此错误。在您的循环中,d是一个字符串,您正尝试使用另一个字符串而不是int来访问它的值。

你明白了吗?