根据键值将字典拆分为两个字典,并存储到单独的字典中

时间:2017-09-29 18:38:51

标签: python-2.7 dictionary

您好我根本不熟悉Python,我需要帮助操作字典。有些问题与我的问题类似,但它们不是解决我问题的可靠解决方案。请考虑我的问题我真的很感激帮助。

我确信有更好的方法可以做到这一点,但这是我能够考虑解决问题的唯一方法。我已经在csv文件中读到了字典。然后我将该字典的值打印到命令提示符中。我喜欢它在打印时如何将每行分开。如何仅从字典中提取与列表中随机生成的键行值匹配的行?这篇文章底部的最后两篇评论总结了我被困的地方。

以下是该计划的输出:

enter image description here

#1. read in text file using inputFileName
#should take in python argument link python decisionTree.py [trainingSetSize] 

import sys, csv, random
print "you entered these arguments", sys.argv
inputFileName = sys.argv[1]

#2. Set the trainingSetSize to desired input number
trainingSetSize = int(sys.argv[2])


#create a list variable to store the training set row key values
trainingSetList = []

text_file = open(inputFileName, "r")
numberOfRows = len(text_file.readlines()) - 1
print numberOfRows
text_file.close()

trainingSetListHoldsKeys = random.sample(range(numberOfRows), trainingSetSize)
print str(trainingSetListHoldsKeys).strip('[]')

with open(inputFileName as csvfile:
     reader = csv.DictReader(csvfile)
     print reader

     for row in reader:
          print(row['GoodGrades'], row['GoodLetters'], row['GoodSAT'], row['IsRich'], row['HasScholarship'], row['ParentAlum'], row['SchoolActivities'], row['CLASS'], row['R'])

# Extract the rows with the desired keys from trainingSetListHoldsKeys into the training set 
# The remaining rows need to be stored in separate dictionary for the testing set

1 个答案:

答案 0 :(得分:0)

我重新安排了一些代码并创建了两个单独的词典。

f = open(inputFileName)

csv_f = csv.reader(f)

count = 0
trainingSet = {count: ''}
testingSet = {count: ''}
for row in csv_f:
    if count in trainingSetListHoldsKeys:
        print row
        trainingSet[count] = row
    else:
        testingSet[count] = row

    count = count + 1

print trainingSet

print '---------\n\n\n---------'

print testingSet

print '---------'