我在一系列循环中使用列表和字典动态创建变量。这允许我根据if条件为这些字典分配不同的值。为了便于演示,我删除了循环并硬编码了一些值,如下所示:
import requests
url = 'http://www.whoscored.com/StatisticsFeed/1/GetTeamStatistics'
params = {
'category': 'tackles',
'subcategory': 'success',
'statsAccumulationType': '0',
'field': 'Overall',
'tournamentOptions': '',
'timeOfTheGameStart': '0',
'timeOfTheGameEnd': '5',
'teamIds': '',
'stageId': '9155',
'sortBy': 'Rating',
'sortAscending': '',
'page': '1',
'numberOfTeamsToPick': '',
'isCurrent': 'true',
'formation': ''
}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
'Host': 'www.whoscored.com',
'Referer': 'http://www.whoscored.com/'}
responser = requests.get(url, params=params, headers=headers)
responser = responser.json()
teamStatDicts = responser[u'teamTableStats']
for statDict in teamStatDicts:
mykey2 = ['tackles','success','0','Overall','0','5','9155','Rating','1','true']
mykey3 = {}
mykey3[mykey2] = ("{challengeLost},{tackleWonTotal},{tackleTotalAttempted},".decode('cp1252').format(**statDict))
运行此代码时,出现以下错误:
^{pr2}$有人能告诉我这个错误的原因是什么,我能做些什么来纠正它吗?在
谢谢
你不能用列表作为字典中的键,因为它是可以修改的,想想如果是这样的话,字典会怎么样!在
相反,只需将此作为元组:
参考:参见“散列”here的定义。在
我不能想出一个原始的答案,但是这里有一些来自python wiki的东西
所以如果你能把mykey2改成这样的元组。你可以用它作为字典的键。
mykey2 = ('tackles','success','0','Overall','0','5','9155','Rating','1','true')
也谢谢。我不知道Python能做到。:)我向你学习!在
相关问题 更多 >
编程相关推荐