Я — новичок в питоне, поэтому если вопрос глупый, не обессудьте.
Есть код:
def sumByLocations(self):
resultDictionary = dict()
while (1):
currentRow = self.cursor.fetchone()
if currentRow == None: break
number, location = currentRow
if location in resultDictionary.keys():
resultDictionary[location] += number
else:
resultDictionary.update(location = number)
return resultDictionary.items()
Соответственно, когда я добавляю новый запись в словарь resultDictionary.update(location = number),
то добавляется именно слово 'location' как ключ. а мне надо, чтобы как ключ добавлялось значение location (например, 'RUSSIA')
Что и где я делаю неправильно?
Re: Python: проблема с методом update в dictionary
От:
Аноним
Дата:
05.02.09 18:48
Оценка:
Здравствуйте, Аноним, Вы писали:
А>Я — новичок в питоне, поэтому если вопрос глупый, не обессудьте. А>Есть код: А> def sumByLocations(self): А> resultDictionary = dict() А> while (1): А> currentRow = self.cursor.fetchone() А> if currentRow == None: break А> number, location = currentRow А> if location in resultDictionary.keys(): А> resultDictionary[location] += number А> else: А> resultDictionary.update(location = number) А> return resultDictionary.items()
А>Соответственно, когда я добавляю новый запись в словарь resultDictionary.update(location = number), А>то добавляется именно слово 'location' как ключ. а мне надо, чтобы как ключ добавлялось значение location (например, 'RUSSIA') А>Что и где я делаю неправильно?
уппс, поправлю отступы
def sumByLocations(self):
resultDictionary = dict()
while (1):
currentRow = self.cursor.fetchone()
if currentRow == None: break
number, location = currentRow
if location in resultDictionary.keys():
resultDictionary[location] += number
else:
resultDictionary.update(location = number)
return resultDictionary.items()
Re[2]: Python: проблема с методом update в dictionary
От:
Аноним
Дата:
05.02.09 19:03
Оценка:
Здравствуйте, Аноним, Вы писали:
А>Здравствуйте, Аноним, Вы писали:
А>>Я — новичок в питоне, поэтому если вопрос глупый, не обессудьте. А>>Есть код: А>> def sumByLocations(self): А>> resultDictionary = dict() А>> while (1): А>> currentRow = self.cursor.fetchone() А>> if currentRow == None: break А>> number, location = currentRow А>> if location in resultDictionary.keys(): А>> resultDictionary[location] += number А>> else: А>> resultDictionary.update(location = number) А>> return resultDictionary.items()
А>>Соответственно, когда я добавляю новый запись в словарь resultDictionary.update(location = number), А>>то добавляется именно слово 'location' как ключ. а мне надо, чтобы как ключ добавлялось значение location (например, 'RUSSIA') А>>Что и где я делаю неправильно? А>уппс, поправлю отступы А> def sumByLocations(self): А> resultDictionary = dict() А> while (1): А> currentRow = self.cursor.fetchone() А> if currentRow == None: break А> number, location = currentRow А> if location in resultDictionary.keys(): А> resultDictionary[location] += number А> else: А> resultDictionary.update(location = number) А> return resultDictionary.items()
блин опять, отступы съехалии...
но все заработало) большое спасибо героям))
Re[3]: Python: проблема с методом update в dictionary
Re: Python: проблема с методом update в dictionary
От:
Аноним
Дата:
06.02.09 06:50
Оценка:
Здравствуйте, Аноним, Вы писали:
А>Я — новичок в питоне, поэтому если вопрос глупый, не обессудьте. А>Есть код:
def sumByLocations(self):
resultDictionary = dict()
while (1):
currentRow = self.cursor.fetchone()
if currentRow == None: break
number, location = currentRow
if location in resultDictionary.keys():
resultDictionary[location] += number
else:
resultDictionary.update(location = number)
return resultDictionary.items()
А>Соответственно, когда я добавляю новый запись в словарь resultDictionary.update(location = number), А>то добавляется именно слово 'location' как ключ. а мне надо, чтобы как ключ добавлялось значение location (например, 'RUSSIA') А>Что и где я делаю неправильно?
Так и должно быть, ибо:
If keyword arguments are specified, the dictionary is then is updated with those key/value pairs: d.update(red=1, blue=2)
Я бы не заморачивался с update в данном случае, а написал бы просто:
resultDictionary[location] = number
И все пойдет по плану... (C)Егор Летов
Re: Python: проблема с методом update в dictionary
Здравствуйте, Аноним, Вы писали:
А>Я — новичок в питоне, поэтому если вопрос глупый, не обессудьте. А>Есть код:
А> def sumByLocations(self):
А> resultDictionary = dict()
А> while (1):
А> currentRow = self.cursor.fetchone()
А> if currentRow == None: break
А> number, location = currentRow
А> if location in resultDictionary.keys():
А> resultDictionary[location] += number
А> else:
А> resultDictionary.update(location = number)
А> return resultDictionary.items()
А>Соответственно, когда я добавляю новый запись в словарь resultDictionary.update(location = number), А>то добавляется именно слово 'location' как ключ. а мне надо, чтобы как ключ добавлялось значение location (например, 'RUSSIA') А>Что и где я делаю неправильно?
Я бы сделал так.
А>1 def sumByLocations(self):
А>2 resultDictionary = dict()
>>2 for currentRow in self.cursor:
А>4 number, location = currentRow
>>5 resultDictionary[location] = number + resultDictionary.get(location, 0)
А>6 return resultDictionary.items()
Строка 4 нужна как комментарий, что мы какие-то строчки перебираем.
А в строке 6 я бы вернул словарь, а уж вызывающий код может его преобразовывать, как ему хочется.