If you are using python 3.5 or greater you can merge your dictionaries using the following syntax:

appointment1 = { 'soccer' : {
                        'day' : 20,
                       'month' : 'april'
                       }

            }
appointment2 = { 'soccer' : {
                        'day' : 20,
                        'month' : 'april'
                       },
              'gym' : {
                        'day' : 5,
                        'month' : 'may'
                       }
            }
appointment = {**appointment1,**appointment2}
Answer from mohamad khajezade on Stack Overflow
🌐
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 - In this case, using a list to store the dictionaries can be cumbersome and you should use nested dictionaries instead. ... I love that someone has took time into looking at Dictionaries, because most of the time people forget about them. In terms of Dictionaries. ... You can modify a dictionary value by directly assigning a new value to an existing key or by using the update() my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"} ... It's been 2 month since I started learning Python!
Discussions

python - Append nested dictionaries - Stack Overflow
If you have a nested dictionary, where each 'outer' key can map to a dictionary with multiple keys, how do you add a new key to the 'inner' dictionary? For example, I have a list where each element... More on stackoverflow.com
🌐 stackoverflow.com
June 16, 2017
python - Append dictionary to dictionary as nested - Stack Overflow
for iteration, i_parameter in enumerate(list_of_things): # Call Function_a() dict_DFResults = Function_a(i_parameter, matrix) The program iterates over list_of_things with 4 items in it. More on stackoverflow.com
🌐 stackoverflow.com
Nested dictionary. Merging common keys and appending values to list. 0 value isn't appending. Code inside.
Look more closely at your code: for variable in foo[count].keys(): if variable in foo[count].keys(): You're taking each key and then checking if it's one of the keys. Well of course it is. I guess that you didn't mean to do that. (Note also that you don't need the calls to keys() here at all; iterating a dict, and checking membership, work directly on the keys already.) More on reddit.com
🌐 r/learnpython
6
1
November 21, 2021
How do I append values to a nested dictionary in Python? - Stack Overflow
So, the daysOver function is something that I am using to get a value. I want this value to be appended to the dictionary, mydict, to the 'Temp Count' key. More on stackoverflow.com
🌐 stackoverflow.com
January 29, 2022
🌐
LogRocket
blog.logrocket.com › home › intro to python dictionaries
Intro to Python dictionaries - LogRocket Blog
June 4, 2024 - To insert an item into a nested dictionary, you must assign or append a key and a value to the dictionary. If the item’s key already exists in the dictionary, then only the key-value updates.
🌐
Linux Tip
linuxscrew.com › home › programming › python › how to add/append items to a dictionary in python [examples]
How to Add/Append Items to a Dictionary in Python [Examples]
November 4, 2021 - The above code demonstrates appending to a nested dictionary, resulting in the following: myDictionary = { "name": "Fred", "animal": "cat", "colour": "red", "age": 3, "collar": { "colour": "blue", "style": "studded", "length": 20, "width": 3 } } SHARE: Related Articles · Appending Items to a List in Python with append() [Examples] How To Remove Items From A List in Python (With Examples) How to Slice a Dictionary in Python, With Examples ·
🌐
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
Find elsewhere
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - Learn to create a Nested Dictionary in Python, access change add and remove nested dictionary items, iterate through a nested dictionary and more.
🌐
Reddit
reddit.com › r/learnpython › nested dictionary. merging common keys and appending values to list. 0 value isn't appending. code inside.
r/learnpython on Reddit: Nested dictionary. Merging common keys and appending values to list. 0 value isn't appending. Code inside.
November 21, 2021 -

Code: https://pastebin.com/GJn74YX5

I have a nested dictionary with the data structure:

foo[count] [string variable] = value

foo = { 0 : { "a": 2,	"b": 5,	"c": 6},
        1 : { "a": 3,	"b": 8,	"d": 9},
        2 : { "b": 5,	"d": 9,	"c": 3}}

I want to take common values of these dicts and combine common values to the appropriate key variable. Perhaps doable in a new dict. If the common variable is not available for that specific count, it will add a 0. All values should be the same length in the new dict. To to look like this:

{ "a": [2, 3, 0], "b": [5, 8, 5], "c":[6, 0, 3], "d": [0,9,9] }

My approach:

  1. Create newdict a defaultdict(list) so i can check if key exists and append to the list like seen above. This will be the final dict I want

     newdict = defaultdict(list)  
  2. Create the following for loop to append to the new dict:

    for count in foo.keys():
        for variable in foo[count].keys():
            if variable in foo[count].keys():
                newdict[variable].append(foo[count].get(variable))
            elif variable not in foo[count].keys():
                newdict[variable].append(0)		
            else:
                newdict[variable] = foo[count].get(variable)

My problem:

Output:

{ "a": [2, 3], "b": [5, 8, 5], "c":[6, 3], "d": [9,9] }
  • The newdict seem to merge all the values but it seems to always go toward the first if statement

  • The elif block is never reached -- 0 is never appended to the list

  • The else block is also never reached but it seems to be appending right so might not be a big deal(?)

I spent hours and cant seem to wrap my ahead why 0 isn't appending. Any help is appreciated. Thank you in advance!

🌐
Stack Overflow
stackoverflow.com › questions › 70902639 › how-do-i-append-values-to-a-nested-dictionary-in-python
How do I append values to a nested dictionary in Python? - Stack Overflow
January 29, 2022 - def writeTempsData(Temperature): mydict = { '1': {'Location': 'Adelaide','Temp Count':''}, '2': {'Location': 'Perth','Temp Count':''}, '3': {'Location': '
🌐
GeeksforGeeks
geeksforgeeks.org › python-nested-dictionary
Python Nested Dictionary - GeeksforGeeks
June 10, 2023 - Updating a nested dictionary involves modifying its structure or content by:Adding new key-value pairs to any level of the nested structure.Modifying existing values associated with specifi ...
🌐
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 nested dictionary.
Top answer
1 of 2
2

here's solution without defaultdict:

d = {'Spring Savings 0413' : {1 : 3000, 2: 2000, 4:1000}, 
 'Back to School 0812' : {1: 4000, 3:3000, 4:2000}}

r = {}

for s, l in d.items():
    for i in range(1, 5):
        if i not in r: r[i] = {}
        r[i][s] = l.get(i, 0) + r.get(i - 1, {}).get(s, 0)

{1: {'Back to School 0812': 4000, 'Spring Savings 0413': 3000},
 2: {'Back to School 0812': 4000, 'Spring Savings 0413': 5000},
 3: {'Back to School 0812': 7000, 'Spring Savings 0413': 5000},
 4: {'Back to School 0812': 9000, 'Spring Savings 0413': 6000}}
2 of 2
1

You are overwriting the entry for each key on every loop using by_day[i] = {}. You should rather check for existence of key, in which case, you should update the existing dict.

Or alternatively, use a collections.defaultdict:

>>> by_sale = {'Spring Savings 0413' : {1 : 3000, 2: 2000, 4:1000}, 'Back to School 0812' : {1: 4000, 3:3000, 4:2000}}
>>> 
>>> 
>>> from collections import defaultdict
>>> 
>>> by_day = defaultdict(dict)
>>> for sale, sale_info in by_sale.iteritems():
...     running_total = 0
...     for i in range(1,5):
...         daily_amount = sale_info.get(i,0)
...         running_total += daily_amount
...         by_day[i].update({sale:running_total})
... 
>>> 
>>> dict(by_day)
{1: {'Spring Savings 0413': 3000, 'Back to School 0812': 4000}, 
 2: {'Spring Savings 0413': 5000, 'Back to School 0812': 4000}, 
 3: {'Spring Savings 0413': 5000, 'Back to School 0812': 7000}, 
 4: {'Spring Savings 0413': 6000, 'Back to School 0812': 9000}}

You should use range(1, 5) instead. range(1, 4) gives - [1, 2, 3].

🌐
Career Karma
careerkarma.com › blog › python › python nested dictionary: a how-to guide
Python Nested Dictionary: A How-To Guide | Career Karma
December 1, 2023 - Our dictionary is stored in the Python variable “ice_cream_flavors”. We added a key called discount to the dictionary. The index position of this key is 0. We set the value of this key to True. Then, we printed out the dictionary with the index value 0 in our ice_cream_flavors nested dictionary.
🌐
GitHub
gist.github.com › PatrikHlobil › 9d045e43fe44df2d5fd8b570f9fd78cc
Get all keys or values of a nested dictionary or list in Python · GitHub
def get_keys(dictionary): result = [] for key, value in dictionary.items(): if type(value) is dict: new_keys = get_keys(value) result.append(key) for innerkey in new_keys: result.append(f'{key}/{innerkey}') else: result.append(key) return result · Copy link · Copy Markdown · Very useful thanks! Copy link · Copy Markdown · I used @mh-malekpour code and added support for objects that are nested inside of arrays.