[英]how to select the value from list pair in python
我有下面的列表,試圖提取列表對的值,例如我需要知道list
中的average_buy_price
是多少。
[{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
目前它給出了error
。
TypeError: list indices must be integers or slices, not str
上面的 output 來自系統,我只需要 select 我需要的值。 example ( 'average_buy_price')
需要得到 output 的值。 '6755.03
我注意到的一件事是,它以 [ 開始並以 ] 結束,為了測試我剛剛從 { 復制到 } 我能夠提取值,看起來像我使用時的語法問題。 需要幫助。
在您的列表中只有一dictionary
。 要從字典訪問average_buy_price
,請嘗試:
test_list = [{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
print(test_list[0].get('average_buy_price')) # output 6755.03
您有一個包含單個字典的列表。 如果要訪問字典的元素,首先索引列表: test_list[0]['average_buy_price']
是的,只要你有方括號,它就是一個list
,所以它不能用字符串索引。
去掉方括號(只保留花括號)。 它不再是一個list
,而是一個dictionary ,可以用字符串鍵值索引。
列表中的每個元素實際上都是一本字典。 因此,遍歷列表,然后獲取鍵值對。
myList= [{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
for d in myList:
for k, v in d.items():
print(k,': ',v)
Output:
enabled : True
total_buy_quantity : 45
average_buy_price : 6755.03
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.