Python 如何从字典中删除键和值浮动
如何删除所有小于5的键和值? 现在我得到了错误“RuntimeError:dictionary在迭代过程中更改了大小”Python 如何从字典中删除键和值浮动,python,dictionary,floating-point,Python,Dictionary,Floating Point,如何删除所有小于5的键和值? 现在我得到了错误“RuntimeError:dictionary在迭代过程中更改了大小” 有什么方法可以使它更有效吗?在迭代dict时不能对其进行变异 您可以迭代密钥的副本: import csv price = [] score = [] numPrice = [] numScore = [] with open(r'C:\Users\Testing\Desktop\Test.csv') as f: reader = csv.DictReader(f)
有什么方法可以使它更有效吗?在迭代dict时不能对其进行变异 您可以迭代密钥的副本:
import csv
price = []
score = []
numPrice = []
numScore = []
with open(r'C:\Users\Testing\Desktop\Test.csv') as f:
reader = csv.DictReader(f)
for row in reader:
price.append(row['price'])
score.append(row['helpfulness_score'])
for item in price:
numPrice.append(float(item))
for item in score:
numScore.append(float(item))
finalDict = dict(zip(numScore,numPrice))
for k in finalDict:
if k > 5:
finalDict.pop(k)
或者使用dict理解,而使用筛选出大于5的键的筛选器:
for k in list(finalDict):
if k > 5:
finalDict.pop(k)
finalDict={k:v代表k,v在zip(numcore,numPrice)中,如果k您可以尝试此操作,而不是在将项目存储到字典中之前弹出项目
finalDict = {k: v for k, v in zip(numScore, numPrice) if k <= 5}
在任何情况下,除非您需要将所有{key:value}
对存储在finalDict
中进行某些处理,否则我建议只使用第一种方法
看见
import csv
finalDict = {}
with open(r'C:\Users\Testing\Desktop\Test.csv') as f:
reader = csv.DictReader(f)
for row in reader:
price = float(row['price']) # converting string to float
score = float(row['helpfulness_score']) # converting string to float
if score <= 5: # checking if the score is less than or equal to five
finalDict[score] = price # stores the key, value pair
popList = [] # list to store the keys to pop
for k in finalDict:
if k > 5:
popList.append(k) # adding keys which will be popped later
for key in popList:
finalDict.pop(key) # popping each key in the popList