I think what you're trying to do is make a nested dictionary. If I understand your input correctly, your code could be fixed just by setting report_dict[row[0]] to an empty dict, by changing

report_dict[row[0]] = row[3]

to

report_dict[row[0]] = {}

This would make the next line,

report_dict[row[0]][row[3]] = row[1]

add the key row[3] with value row[1] to the dictionary report_dict[row[0]]. This would give us:

report_dict = {row[0]: {row[3]: row[1]}, ...}

which I think is your expected output.

Answer from CDJB on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_dictionaries_nested.asp
Python - Nested Dictionaries
To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary: ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Reddit
reddit.com › r/learnpython › adding new values to existing keys in nested dictionary
Adding new values to existing keys in nested dictionary : r/learnpython
July 31, 2023 - Share ... You do it just the same as appending to any list; using the append method. For instance, assuming Spain is the fourth item in the log: ... After you have found the dictionary for Spain you get the list under the "cities" key and append the new city string.
Top answer
1 of 10
426

A nested dict is a dictionary within a dictionary. A very simple thing.

Copy>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d['dict1']['innerkey2'] = 'value2'
>>> d
{'dict1': {'innerkey': 'value', 'innerkey2': 'value2'}}

You can also use a defaultdict from the collections package to facilitate creating nested dictionaries.

Copy>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d  # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d)  # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}

You can populate that however you want.

I would recommend in your code something like the following:

Copyd = {}  # can use defaultdict(dict) instead

for row in file_map:
    # derive row key from something 
    # when using defaultdict, we can skip the next step creating a dictionary on row_key
    d[row_key] = {} 
    for idx, col in enumerate(row):
        d[row_key][idx] = col

According to your comment:

may be above code is confusing the question. My problem in nutshell: I have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has these columns. i is kind of key columns for these csvs'. j k l column is empty in a.csv but populated in b.csv. I want to map values of j k l columns using 'i` as key column from b.csv to a.csv file

My suggestion would be something like this (without using defaultdict):

Copya_file = "path/to/a.csv"
b_file = "path/to/b.csv"

# read from file a.csv
with open(a_file) as f:
    # skip headers
    f.next()
    # get first colum as keys
    keys = (line.split(',')[0] for line in f) 

# create empty dictionary:
d = {}

# read from file b.csv
with open(b_file) as f:
    # gather headers except first key header
    headers = f.next().split(',')[1:]
    # iterate lines
    for line in f:
        # gather the colums
        cols = line.strip().split(',')
        # check to make sure this key should be mapped.
        if cols[0] not in keys:
            continue
        # add key to dict
        d[cols[0]] = dict(
            # inner keys are the header names, values are columns
            (headers[idx], v) for idx, v in enumerate(cols[1:]))

Please note though, that for parsing csv files there is a csv module.

2 of 10
70

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

Copyfrom collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - Merging nested dictionaries can be done in two ways, shallow merging and deep merging, depending on the desired outcome. Shallow merging is a straightforward approach where the update() method is used.
🌐
GeeksforGeeks
geeksforgeeks.org › python-nested-dictionary
Python Nested Dictionary - GeeksforGeeks
June 10, 2023 - Nested dictionary 1- {'Dict1': {}, 'Dict2': {}} Nested dictionary 2- {'Dict1': {'name': 'Ali', 'age': '19'}, 'Dict2': {'name': 'Bob', 'age': '25'}} Nested dictionary 3- {'Dict1': {1: 'G', 2: 'F', 3: 'G'}, 'Dict2': {1: [1, 2], 'Name': 'Geeks'}} The addition of elements to a nested Dictionary can be done in multiple ways.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › home › python › python nested dictionaries
Python Nested Dictionaries
February 21, 2009 - With this method, an empty outer dictionary is initialized, and then populated with dictionaries as values using a loop to define nested dictionaries − · # Define an empty outer dictionary nested_dict = {} # Add key-value pairs to the outer dictionary outer_keys = ["outer_key1", "outer_key2"] for key in outer_keys: nested_dict[key] = {"inner_key1": "value1", "inner_key2": "value2"} print(nested_dict)
🌐
SitePoint
sitepoint.com › python, perl and golang › python
Adding a new key to a nested dictionary in python - Python - SitePoint Forums | Web Development & Design Community
December 21, 2016 - JSON: {'result':[{'key1':'valu... list, like this: dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]} length = len(dict['result']) print(length) data_dict[......
🌐
Programiz
programiz.com › python-programming › nested-dictionary
Python Nested Dictionary (With Examples)
In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age and sex with respective values. Then we print the people[4], to see that the dictionary 4 is added in nested dictionary people. In Python, we use “ del “ statement to delete elements from ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-add-keys-to-nested-dictionary
Add Keys to Nested Dictionary - GeeksforGeeks
July 12, 2025 - If it doesn't, it sets 'rank' to 1 and returns 1 otherwise it returns the existing value of 'rank'. update() directly add or update key-value pairs in a dictionary. When dealing with nested dictionaries, we can use it to insert or modify values at any depth, which is particularly useful when the exact path and values are already known.
🌐
LogRocket
blog.logrocket.com › home › intro to python dictionaries
Intro to Python dictionaries - LogRocket Blog
June 4, 2024 - The new dictionary can then be added as an item in the products parent dictionary. To delete an item from a nested dictionary, you must first retrieve the item using the key and then delete the item using the del() method.
🌐
Medium
medium.com › @ryan_forrester_ › python-nested-dictionaries-complete-guide-8a61b88a2e02
Python Nested Dictionaries: Complete Guide | by ryan | Medium
October 24, 2024 - class ProductCatalog: def __init__(self): self.catalog = { 'electronics': { 'smartphones': { 'iphone_12': { 'name': 'iPhone 12', 'price': 799.99, 'specs': { 'storage': '128GB', 'color': ['Black', 'White', 'Blue'], 'screen': '6.1 inch' }, 'stock': { 'warehouse_1': 50, 'warehouse_2': 30 } } } } } def get_product_price(self, category, subcategory, product): try: return self.catalog[category][subcategory][product]['price'] except KeyError: return None def get_total_stock(self, category, subcategory, product): try: stock = self.catalog[category][subcategory][product]['stock'] return sum(stock.value
🌐
TutorialsPoint
tutorialspoint.com › update-a-nested-dictionary-in-python
Update a Nested Dictionary in Python
Then, we update the value of 'inner_key' within the 'outer_key' in the updated_dict to 'new_value'. Finally, we print the original nested_dict and the updated updated_dict. As you can see from the output, the original nested_dict remains unchanged, while the updated_dict reflects the updated value. Updating a nested dictionary in Python can involve accessing specific keys, merging dictionaries, or using recursive techniques.
Top answer
1 of 1
6

1. General comments

  1. To run the doctests in file.py, just run:

    python -m doctest file.py
    

    (See the documentation for the doctest module where this is explained.)

  2. I said that I didn't understand your question (and indeed I still don't) and you replied, "I really can't see what's wrong with my question." Well, obviously you understand it—you've discussed the problem with your colleague and you've written a solution. But take it from me, your description is not clear to someone like me who has no idea what you are on about.

    For example, what is the "some function" in the first sentence and why do you mention it if it is not relevant? In one place you write about "decomposing" "swept keys" and in another you write about "detonating" them. Are these two different procedures or are they two names for the same procedure? And so on.

    It's not easy to write clear descriptions of complex functions. But it helps if you listen to your readers.

2. The function dict_2_list_of_keys

  1. It took me a while to figure out that "2" here is not actually a number but a pun for "to". Write to instead of 2: it's only one character longer.

  2. The function does not actually return a list of keys as suggested by the name: it actually returns a list of lists of keys.

  3. The docstring is quite obscure. It returns a "list containing lists describing the dictionary nodes' paths". When you write containing, do you mean containing all of them? What is a dictionary node? (Dictionaries have keys and values but not, as far as I know, nodes.) What is a dictionary nodes' path?

  4. There's no point writing:

    for k in iter(d):
    

    when you could just write:

    for k in d:
    
  5. But having written that, since you look up the value d[k], it would be better to iterate over the keys and values of the dictionary, and avoid the lookups:

    for k, v in d.items():
    
  6. Writing loc * 1 is a very obscure way to take a copy of a list. It would be clearer if you wrote loc.copy() (Python 3) or copy.copy(loc) (Python 2).

  7. The doctest fails:

    Failed example:
        dict_2_list_of_keys({'k1': 'v1', 'k2': {'k21': 'v21', 'k22': 'v22'}})
    Exception raised:
        Traceback (most recent call last):
          File "/python3.4/doctest.py", line 1324, in __run
            compileflags, 1), test.globs)
          File "<doctest cr55588.dict_2_list_of_keys[0]>", line 1, in <module>
            dict_2_list_of_keys({'k1': 'v1', 'k2': {'k21': 'v21', 'k22': 'v22'}})
        TypeError: dict_2_list_of_keys() missing 2 required positional arguments: 'l' and 'loc'
    
  8. Even with the missing arguments added, the doctest still fails:

    Failed example:
        dict_2_list_of_keys({'k1': 'v1', 'k2': {'k21': 'v21', 'k22': 'v22'}}, [], [])
    Expected:
        [['k1'], ['k2', 'k21'], ['k2', 'k22']]
    Got:
        [['k1'], ['k2'], ['k2', 'k21'], ['k2', 'k22']]
    

    Is the doctest correct and the code wrong, or is it the other way round? The docstring is not written clearly enough for me to tell! So I'm going to assume that the doctest is right and the code is wrong. At least I understand the doctest.

    So the way to fix this is to write the loop like this:

    for k, v in d.items():
        loc.append(k)
        if isinstance(v, dict):
            dict_2_list_of_keys(v, l, loc)
        else:
            l.append(loc.copy())
        loc.pop()
    
  9. But even with that fix, the doctest still doesn't pass:

    Failed example:
        dict_2_list_of_keys({'k1': 'v1', 'k2': {'k21': 'v21', 'k22': 'v22'}}, [], [])
    Expected:
        [['k1'], ['k2', 'k21'], ['k2', 'k22']]
    Got:
        [['k2', 'k22'], ['k2', 'k21'], ['k1']]
    

    That's because iteration over a dictionary is not guaranteed to happen in any particular order. So in order to have a consistently reproducible doctest, you should sort the results.

  10. When producing a series of results in Python, it is usually more convenient to generate the results using the yield statement, rather than appending them to a list as you do. This avoids the need to pass in the l argument.

Putting all this together, I'd write the function like this:

def key_sequences(d):
    """Given a (possibly nested) dictionary d, generate tuples giving the
    sequence of keys needed to reach each non-dictionary value in d
    (and its nested sub-dictionaries, if any).

    For example, given the dictionary:

    >>> d = {1: 0, 2: {3: 0, 4: {5: 0}}, 6: 0}

    there are non-dictionary values at d[1], d[2][3], d[2][4][5], and
    d[6], and so:

    >>> sorted(key_sequences(d))
    [(1,), (2, 3), (2, 4, 5), (6,)]

    """
    for k, v in d.items():
        if isinstance(v, dict):
            for seq in key_sequences(v):
                yield (k,) + seq
        else:
            yield (k,)