imhamza3333
imhamza3333

Reputation: 174

get the result in 1 dict in the place of 2 dict

I want to use only 1 dict (result) in the place of 2 dict (males, females), then everything goes in that dict properly and then I just print them.

Can anyone help me with this, please?

import csv

males = {}
females = {}

with open('1000 Records.csv') as csv_file:
    csv_reader = csv.reader(csv_file)

    for row in csv_reader:
        year_of_joining = int(row[17])
        quarter_of_joining = row[15]
        gender = row[5]
        result = males if gender == 'M' else females

        if year_of_joining not in result:
            result[year_of_joining] = {f'Q{i + 1}': 0 for i in range(4)}

        result[year_of_joining][quarter_of_joining] += 1


years = list(males.keys()) + list(females.keys())
years = sorted(list(set(years)))

for year in years:
    count = [males.get(year, 0), females.get(year, 0)]
    print("People who join in H1 and H2: %s: %s" % (year, count))

Upvotes: 2

Views: 81

Answers (1)

Karol Zlot
Karol Zlot

Reputation: 4035

Please let me know if this is what you wanted to achieve, because the question is not fully clear for me.

import csv


results={'males':{},'females':{}}

with open('1000 Records.csv') as csv_file:
    csv_reader = csv.reader(csv_file)

    for row in csv_reader:
        year_of_joining = int(row[17])
        quarter_of_joining = row[15]
        gender = 'males' if row[5] == 'M' else 'females'
        

        if year_of_joining not in results[gender]:
            results[gender][year_of_joining] = {f'Q{i + 1}': 0 for i in range(4)}
            
        results[gender][year_of_joining][quarter_of_joining] += 1


years = list(results['males'].keys()) + list(results['females'].keys())
years = sorted(list(set(years)))

for year in years:
    count = [results['males'].get(year, 0), results['females'].get(year, 0)]
    print("People who join in H1 and H2: %s: %s" % (year, count))

Upvotes: 2

Related Questions