我尝试创建的代码应该有两个键:
("democrats"("republicans"
我几乎得到了所有正确的数据,我只是没有关键字典。这是我目前正在处理的:
def getPartyUserTwitterUsage(tweetFile):
import csv
myFile = open(tweetFile,"r") # opening file in read
csvReader = csv.reader(myFile,delimiter=",") # splitting for ','
next(csvReader) # skipping header
tweetList = {}
repTweet = 0
demoTweet = 0
for row in csvReader: # iterating through file
if (row[1] == 'R'):
if (row[0] not in tweetList):
tweetList[row[0]] = 1
else:
tweetList[row[0]] += 1
if (row[1] == 'D'):
if (row[0] not in tweetList):
tweetList[row[0]] = 1
else:
tweetList[row[0]] += 1
return tweetList
这个函数:getPartyUserTwitterUsage("tweet - 2020 (2) .csv")
的回报:
{'ChrisMurphyCT': 1000,
'SenBlumenthal': 1000,
'SenatorCarper': 1000,
'ChrisCoons': 1000,
'brianschatz': 1000,
'maziehirono': 1000,
'SenatorDurbin': 1000,
'SenatorHarkin': 1000,
'lisamurkowski': 1000,
'JeffFlake': 1000,
'marcorubio': 1000,
'MikeCrapo': 958,
'SenatorRisch': 1000,
'ChuckGrassley': 1000,
'SenPatRoberts': 1000,
'JerryMoran': 1000}
这是我期望的输出:
{'Republicans': {'lisamurkowski': 1000,
'JeffFlake': 1000,
'marcorubio': 1000,
'MikeCrapo': 958,
'SenatorRisch': 1000,
'ChuckGrassley': 1000,
'SenPatRoberts': 1000,
'JerryMoran': 1000},
'Democrats': {'ChrisMurphyCT': 1000,
'SenBlumenthal': 1000,
'SenatorCarper': 1000,
'ChrisCoons': 1000,
'brianschatz': 1000,
'maziehirono': 1000,
'SenatorDurbin': 1000,
'SenatorHarkin': 1000}}
您需要在插入条目之前创建密钥:Republicans
和Democrats
。
...
tweetList["Republicans"] = {}
tweetList["Democrats"] = {}
for row in csvReader: # iterating through file
if (row[1] == 'R'):
if (row[0] not in tweetList["Republicans"]):
tweetList["Republicans"][row[0]] = 1
else:
tweetList["Republicans"][row[0]] += 1
if (row[1] == 'D'):
if (row[0] not in tweetList["Democrats"]):
tweetList["Democrats"][row[0]] = 1
else:
tweetList["Democrats"][row[0]] += 1
return tweetList