Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8470653
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T16:34:46+00:00 2026-06-10T16:34:46+00:00

Total Python noob here, probably missing something obvious. I’ve searched everywhere and haven’t found

  • 0

Total Python noob here, probably missing something obvious. I’ve searched everywhere and haven’t found a solution yet, so I thought I’d ask for some help.

I’m trying to write a function that will build a nested dictionary from a large csv file. The input file is in the following format:

Product,Price,Cost,Brand,
blue widget,5,4,sony,
red widget,6,5,sony,
green widget,7,5,microsoft,
purple widget,7,6,microsoft,

etc…

The output dictionary I need would look like:

projects = { `<Brand>`: { `<Product>`: { 'Price': `<Price>`, 'Cost': `<Cost>` },},}

But obviously with many different brands containing different products. In the input file, the data is ordered alphabetically by brand name, but I know that it becomes unordered as soon as DictReader executes, so I definitely need a better way to handle the duplicates. The if statement as written is redundant and unnecessary.

Here’s the non-working, useless code I have so far:

def build_dict(source_file):
  projects = {}
  headers = ['Product', 'Price', 'Cost', 'Brand']
  reader = csv.DictReader(open(source_file), fieldnames = headers, dialect = 'excel')
  current_brand = 'None'
  for row in reader:
    if Brand != current_brand:
      current_brand = Brand
    projects[Brand] = {Product: {'Price': Price, 'Cost': Cost}}
  return projects

source_file = 'merged.csv'
print build_dict(source_file)

I have of course imported the csv module at the top of the file.

What’s the best way to do this? I feel like I’m way off course, but there is very little information available about creating nested dicts from a CSV, and the examples that are out there are highly specific and tend not to go into detail about why the solution actually works, so as someone new to Python, it’s a little hard to draw conclusions.

Also, the input csv file doesn’t normally have headers, but for the sake of trying to get a working version of this function, I manually inserted a header row. Ideally, there would be some code that assigns the headers.

Any help/direction/recommendation is much appreciated, thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T16:34:48+00:00Added an answer on June 10, 2026 at 4:34 pm
    import csv
    from collections import defaultdict
    
    def build_dict(source_file):
        projects = defaultdict(dict)
        headers = ['Product', 'Price', 'Cost', 'Brand']
        with open(source_file, 'rb') as fp:
            reader = csv.DictReader(fp, fieldnames=headers, dialect='excel',
                                    skipinitialspace=True)
            for rowdict in reader:
                if None in rowdict:
                    del rowdict[None]
                brand = rowdict.pop("Brand")
                product = rowdict.pop("Product")
                projects[brand][product] = rowdict
        return dict(projects)
    
    source_file = 'merged.csv'
    print build_dict(source_file)
    

    produces

    {'microsoft': {'green widget': {'Cost': '5', 'Price': '7'},
                   'purple widget': {'Cost': '6', 'Price': '7'}},
     'sony': {'blue widget': {'Cost': '4', 'Price': '5'},
              'red widget': {'Cost': '5', 'Price': '6'}}}
    

    from your input data (where merged.csv doesn’t have the headers, only the data.)

    I used a defaultdict here, which is just like a dictionary but when you refer to a key that doesn’t exist instead of raising an Exception it simply makes a default value, in this case a dict. Then I get out — and remove — Brand and Product, and store the remainder.

    All that’s left I think would be to turn the cost and price into numbers instead of strings.

    [modified to use DictReader directly rather than reader]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Total noob here with javascript. I'm trying to alter a function. This is the
Total noob here. This is my first c# attempt, its a console application that
Total noob question, but here. CSS .product__specfield_8_arrow { /*background-image:url(../../upload/orng_bg_arrow.png); background-repeat:no-repeat;*/ background-color:#fc0; width:50px !important; height:33px
I want a one-liner solution in Python of the following code, but how? total
So I am a total noob at python so im sorry if im not
I'm a total python noob so please bear with me. I want to have
I'm new to python and a total noob with programming so bear with. If
I want to quickly find the total size of any folder using python. import
Total noobie question here. I'm just learning Java, and studying passing arguments to functions.
Total noob to anything lower-level than Java, diving into iPhone audio, and realing from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.