Ivan Galin Ivan Galin - 1 month ago 17
Python Question

Iteration variable inside the generator dictionary

Good day!
There is a question about iterating inside the generator dictionaries in python:

sort_dict = {select_keys: {rows: {j: item for item in self.csv_dict.values() if item.get(select_keys) == rows} for rows in keys}}


It is necessary that the variable
j
increases until it vyrozhenie data are recorded:

for item in self.csv_dict.values () if item.get (select_keys) == rows}


I'm new to python, so I apologize for the stupid question. I for a long time I fight over this trivial issue, but it should perform - because this problem needs to be put now.

There is a class that deals piercing file csv:

`import csv

class CSV():

def __init__(self, file_path):
super().__init__()
self.file_path = file_path
self.csv_dict = {}

"""Данный метод парсит переданный в класс CSV файл"""
def parseeCSV(self):
print('\n')
self.getDictCSV()
print(self.getListKeysCSV())
unic_key = self.getUnicValFromCustomKeys('zip')
sort_csv = self.getCsvSortForKeys(unic_key, 'zip')

"""Данный метод создает словарь из переданного в класс CSV файла
Словарь вида {Номер строки(записи){строка(запись)}}
"""
def getDictCSV(self):
i = 0
with open(self.file_path, 'r') as csv_desctiptor:
csv_obj = csv.DictReader(csv_desctiptor)
for csv_dict in csv_obj:
self.csv_dict[i] = csv_dict
i = i + 1
del csv_desctiptor
return True

"""Данный метод возвращает все ключи из словаря self.csv_dict[0]"""
def getListKeysCSV(self):
return dict.keys(self.csv_dict[0])

"""Данный метод возвращает уникальные значения по выбранным полям"""
def getUnicValFromCustomKeys(self, keys):
i = 0
val_key = {}
while i < len(self.csv_dict):
val_key[i] = self.csv_dict[i].get(keys)
unic_val_key = set(val_key.values())
i = i + 1
return unic_val_key

def getCsvSortForKeys(self, keys, select_keys):
#sort_dict = {select_keys: {rows: '' for rows in keys}}
i = 0`


It parses the CSV type of file:

street,city,zip,state,beds,baths,sq__ft,type,sale_date,price,latitude,longitude
3526 HIGH ST,SACRAMENTO,95838,CA,2,1,836,Residential,Wed May 21 00:00:00 EDT 2008,59222,38.631913,-121.434879


At the same time he has to do Dictionary type:

csv_dict[key_select][key_select_val][num-element][element_csv_string]


For example:
csv_dict['zip']['95838'][1][3526 HIGH ST,SACRAMENTO,95838,CA,2,1,836,Residential,Wed May 21 00:00:00 EDT 2008,59222,38.631913,-121.434879


Thanks in advance, and I apologize for the stupid questions.

Answer

Please , explain your question.

I am not able to collect any reference of j in your code. And also the code seems wrongly constructed.

sort_dict = {select_keys: {rows: 
    {j: item for j,item in enumerate(self.csv_dict.values()) 
        if item.get(select_keys) == rows} for rows in keys}}

Hope that helps!

Comments