I have the orders of a platform in a csv file and I want to organize it to put in a database (probably mongodb). So the final data structure may be:
{'user1':
{'meals': {'hamburger': 2}, {'pizza': 1},
{'weekdays': {'monday': 1}},{'tuesday':1}, {'friday': 1}
}
So, I am trying to do a very simple code that organize the number of ocurrencies, but before I want to structure the dictionary keys dinamically. The data is in a csv file
import csv
import pprint
def addKeysNestedDict(dictionary, keys):
# print(dictionary)
if len(keys) > 1:
if keys[0] not in dictionary.keys():
dictionary[keys[0]] = {'meals': '', 'weekdays': ''}
print('inside addKeys IF: ')
print(dictionary)
addKeysNestedDict(dictionary, keys[1:])
else:
dictionary[keys[0]] = {'meals': '', 'weekdays': ''}
print('inside addKeys: ')
print(dictionary) # PRINTS EXPECTED VALUES
return dictionary
def organize_orders(file):
pp = pprint.PrettyPrinter(indent=4)
dict_read = csv.DictReader(file, fieldnames=['name', 'food', 'day'])
list_dict = list(dict_read)
set_names = set()
set_food = set()
set_day = set()
# people = {} # DOESN'T MATTER IF IT IS DECLARED BOFORE
for n in list_dict:
set_names.add(n['name'])
set_food.add(n['food'])
set_day.add(n['day'])
print(addKeysNestedDict({}, list(set_names))) # PRINTS NONE
people = (addKeysNestedDict({}, list(set_names)))
print('people: ')
print(people) # PRINTS NONE
# for s_n in set_names:
# for s_f in set_food:
# for s_d in set_day:
# people[s_n][s_f] = list_dict.count(s_f)
# people[s_n][s_d] = list_dict.count(s_d)
def analyze_log(path_to_file):
with open(path_to_file) as csvfile:
return(organize_orders(csvfile))
analyze_log('some csv file with path')
I culd not figure out why I get none returned from addKeysNestedDict() method, since it prints exactly what I want one line before method return