0

I want to store new data(Key, value) to the nested dictionary. But I don't have any clue how to fix it.

def add(a,b,c,d,container)
    container = {} # as database
    data ={}
    data[a] = [{"first": b, "second": c, "third": d}]

    for e in data:
        if date[date] not in calendar:
            container[date[a]] = {}
            container[date[a]].update([{"first": b, "second": c, "third": d})


add(name, 1, 2, hi, container)
add(name1, 2, 1, hi, container)

I see the following output:

{name: [{"first": 1, "second": 2, "third":hi }]}

{name1: [{"first": 2, "second": 1, "third":hi }]}

I expect the output as:

{name: [{"first": 1, "second": 2, "third":hi }], name1: [{"first": 2, "second": 1, "third":hi }]}

Please help me out!

Neal Lee
  • 3
  • 2

3 Answers3

1

You are creating a local dictionary in your add function. Did you see that?

def add(a,b,c,d,container)
    container = {} # it's a local new dict
    # ...

Instead you should create the dictionary outside of the function, otherwise you'll always get a new dictionary containing only one key. For example:

container = {}

def add(a, b, c, d):
    container[a] = b
    container[c] = d
knh190
  • 2,744
  • 1
  • 16
  • 30
0

i am creating a global_dict which is main dictionary where storing of all the dict element is taken place. for your given problem, if you want to add the data in a dict continously and that dict have same structure, then better: is to create a default dict , and in that dict update the values and finally add that new small dict to the main dict using update method.

def funcion(a,b,c,d, container):
    new_dic={a:[{'first':b,"Second":c,"third":d}]}
    container.update(new_dic)
funcion('name', 1, 2, 'hi')
funcion('name1', 2, 1,'hi')
print(container)

"""
output 

{'name': [{'first': 1, 'Second': 2, 'third': 'hi'}], 
'name1': [{'first': 2, 'Second': 1, 'third': 'hi'}]
}
"
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
-1

I recently made a module for this and posted it on github, it doesnt use recursion so therefore it has absolutely no limits to it. It allows you to edit, add, and remove from a nested dictionary using a keypath. Here it is on stackoverflow(this will answer your question):

How can you add entries, and retrieve, alter, or remove values from specific keys in any nested dictionary without recursion?

and here it is on github:

https://github.com/kthewhispers/Nested-Dictionary-Tools-Python/tree/master/src

Keith Cronin
  • 373
  • 2
  • 9
  • Better to add solution here, your link might get delete in future, which will create problem for the future readers – sahasrara62 Mar 25 '19 at 04:10