How do you create nested dict in Python

0 votes

I have 2 csv files. First one is data file and other one is mapping file. Mapping file has 4 columns Device_Name GDN Device_Type Device_OS These are also the columns which are present in data file and need to be worked upon.

Data file contains data with Device_Name column populated & rest 3 columns blank. Mapping file contains all columns populated. I want my Python code to open both files and for each device name in data file map its GDN, Device_Type & Device_OS value from mapping file.

I know how to use dict when only 2 columns are present (1 is needed to be mapped) but I don't know how to accomplish this when 3 columns need to be mapped.

Following is the code using which I tried to accomplish mapping of Device_Type:

x = dict([])
with open("Pricing Mapping_2013-04-22.csv", "rb") as in_file1:
    file_map = csv.reader(in_file1, delimiter=',')
    for row in file_map:
        typemap = [row[0],row[2]]
        x.append(typemap)
        with open("Pricing_Updated_Cleaned.csv", "rb") as in_file2, open("Data Scraper_GDN.csv", "wb")                                                                                         as out_file:
writer = csv.writer(out_file, delimiter=',')
for row in csv.reader(in_file2, delimiter=','):
    Try:
        row[27] = x[row[11]]
    except KeyError:
        row[27] = "" writer.writerow(row)
        #It returns the Atribute Error.

After some researching, I realized that I need to create a nested dict, but I don't have any idea on how to do this. Please help me in resolving this or nudge me in the right direction to resolve this.

Aug 16, 2018 in Python by bug_seeker
• 15,510 points
3,583 views

1 answer to this question.

0 votes

It is important to remember when using defaultdict and similar nested dict modules such as nested_dict, that looking up a non existent key may inadvertently create a new key entry in the dict and cause a lot of havoc. Here is a Python3 example with nested_dict.

import nested_dict as nd 
nest = nd.nested_dict()
nest[
'outer1']['inner1'] = 'v11'
nest[
'outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
 nest[
'outer1']['wrong_key1']
except KeyError as e:
  
print('exception missing key', e)
  
print('nested dict after lookup with missing key. no exception raised:\n', nest)
# instead convert back to normal dict
 nest_d = nest.to_dict(nest)
try:
  
print('converted to normal dict. Trying to lookup Wrong_key2')
  nest_d[
'outer1']['wrong_key2']
except KeyError as e:
  
print('exception missing key', e)
  
else:
  
print(' no exception raised:\n')
  
# or use dict.keys to check if key in nested dict.
  print('checking with dict.keys')
 print(list(nest['outer1'].keys()))
 
if 'wrong_key3' in list(nest.keys()):
  
print('found wrong_key3')
 else:
  
print(' did not find wrong_key3')

Output is:

original nested dict: {"outer1": {"inner2": "v12", "inner1": "v11"}}
nested dict after lookup
with missing key. no exception raised: {"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 
converted to normal dict.

Trying to lookup Wrong_key2 exception missing key 'wrong_key2' checking with dict.keys ['wrong_key1', 'inner2', 'inner1'] did not find wrong_key3

answered Aug 16, 2018 by Priyaj
• 58,020 points

Related Questions In Python

0 votes
0 answers
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by aryya
• 7,460 points
10,668 views
0 votes
1 answer

How do you express binary literals in Python?

For reference—future Python possibilities: Starting with Python 2.6 you ...READ MORE

answered Aug 14, 2018 in Python by aryya
• 7,460 points
1,037 views
+1 vote
1 answer

How do you express binary literals in Python?

Starting with Python 2.6 you can express ...READ MORE

answered Aug 28, 2018 in Python by Priyaj
• 58,020 points

edited Dec 21, 2023 by Khan Sarfaraz 4,312 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,422 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,042 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

What i found is that you can use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 58,020 points
11,704 views
+2 votes
1 answer

How do you make a block comment in python?

''' This is a multiline comment. I ...READ MORE

answered Aug 23, 2018 in Python by Priyaj
• 58,020 points
960 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP