-3

I want to add a value to a dictionary as the follow:

dic = {'key1': {1: 1},
         'key2': {2: 5, 1: 1},
         'key3': {2: 2, 1: 2},

 }

Want to add a value for "key1" => {3:4, 1:5}

Expected output:

dic = {'key1': {1: 1, 3:4, 1:5},
         'key2': {2: 5, 1: 1},
         'key3': {2: 2, 1: 2},

 }

I tried this but it's not giving me the required output.


dict[key1].append(value)

Would you please help? Thank you in advance!!

Jojo
  • 912
  • 1
  • 7
  • 8
  • 5
    Dictionary keys must be unique. You cannot have `1` be a key in the same dictionary twice, the second value will overwrite the first. – ddejohn Apr 04 '22 at 01:58
  • Please show us what `value` is. Also, dictionaries do not have `append`. – Chris Apr 04 '22 at 02:00
  • I want to add {3:4, 1:5} to the existing value of key1. That will be => 'key1': {1: 1, 3:4, 1:5} – Jojo Apr 04 '22 at 02:04
  • Does this answer your question? [Make a dictionary with duplicate keys in Python](https://stackoverflow.com/questions/10664856/make-a-dictionary-with-duplicate-keys-in-python) – BrokenBenchmark Apr 04 '22 at 02:14

3 Answers3

0

The function you are looking for is dict.update(). However, as was pointed out in the comments, duplicate keys will be silently overwritten.

e.g.

dic["key1"].update({3: 4, 1: 5})

edit:

On the subject of duplicate keys, this SO question provides multiple ways to create a similar behavior: Make a dictionary with duplicate keys in Python

Cresht
  • 1,020
  • 2
  • 6
  • 15
0

In Python 3.5 and later, we can expand a dictionary into another dictionary with:

a = {4: 5}
b = {**a}

If we do this with two dictionaries, we get a merging of them, but with values in the second overwriting values for the same keys in the first.

a = {4: 5}
b = {1: 2, 4: 7}
c = {**a, **b}

c will now be {4: 7, 1: 2}

So you might write:

dict[key1] = {**dict[key1], **{3: 4, 1: 5}}
Chris
  • 26,361
  • 5
  • 21
  • 42
0

append() is a method on the builtin list type. Since the value associated with key1 is the builtin dict type, you won't be able to use append() to achieve this. There is another issue pertaining to your expected output:

{
    1: 1,
    3: 4,
    1: 5,
}

You have two values for the key 1 in this dictionary. In python dictionaries, you can only have a single key. If you wanted to have multiple values for a particular key, there's a few ways to handle this (I would recommend reading up on Hash Tables: Collision Resolution).

For this example, given you were trying to use the append() method, I'm going to assume you wanted to update the value stored to be a list containing [1, 5]. In this case, one way of solving this would be with the following code.

dic = {
    'key1': {1: 1},
    'key2': {2: 5, 1: 1},
    'key3': {2: 2, 1: 2},
 }

key1_new_dict = {
    1: [5],
    3: [4],
}

for key, value in dic['key1'].items():
    if key in key1_new_dict:
        key1_new_dict[key].append(value)
    else:
        key1_new_dict[key] = [value]
award28
  • 46
  • 6