0

So I've a dictionary, I'll call it (a), and I run a loop to sort several other dictionaries throughout the keys of the (a) based on the specific tag each of them has, but this is irrelevant. The problem is, every time the loop runs, the dictionary gets updated, and the previous value gets replaced by the new one. What I want is, I want the loop to keep adding values to the (a) if it finds any new ones, not replace the original value. I tried this:

          dictionary[i] = smalldict

where i is the key needed, and smalldict is the smaller dictionary that I cycle through with a for loop. Whenever this line of code runs, the previous value of smalldict gets replaced by the new one. How do I make it 'append' the newly found value to the key of the dictionary without removing the old one?

tl/dr: How to make a dictionary keep its original values and add in the new ones?

Thanks!

crescent
  • 13
  • 1
  • 3
  • Look into a `defaultdict` so that you add values to a list stored against the key – roganjosh Dec 04 '18 at 19:34
  • Possible duplicate of [list to dictionary conversion with multiple values per key?](https://stackoverflow.com/questions/5378231/list-to-dictionary-conversion-with-multiple-values-per-key) – roganjosh Dec 04 '18 at 19:35
  • 2
    This was the better dupe: https://stackoverflow.com/q/3199171/4799172 oops :/ – roganjosh Dec 04 '18 at 19:36
  • @crescent Welcome to Stackoverflow. The problem is not clear from your question in its current state. Please consider [editing](https://stackoverflow.com/posts/53620178/edit) the question to include more information, possibly add a relevant snippet of code that we can see and reproduce the problem you have, with a [mcve]. For more suggestions to improve your question please review the [help] and [How to ask a good quiestion?](https://stackoverflow.com/help/how-to-ask). – chickity china chinese chicken Dec 04 '18 at 20:56

1 Answers1

0

It's a bit difficult to determine what you are trying to do from your description since you didn't post a desired outcome, but I assume this is what you want to do...

a = {}
b = dict(a=1, b=2, c=3)
c = dict(b=9,c=10, d=99)

def append_items_to_dict(d_in: dict, d_out: dict):
    for k, v in d_in.items():
        d_out.setdefault(k, []).append(v)

append_items_to_dict(b, a)
append_items_to_dict(c, a)
print(a)

result

{'a': [1], 'b': [2, 9], 'c': [3, 10], 'd': [99]}
nicholishen
  • 2,602
  • 2
  • 9
  • 13