2

I have a very large nested dictionary and below I am showing a sample of it.

tmp_dict = {1: {'A': 1, 'B': 2},
            2: {'A': 0, 'B': 0}}

The question is what is any better/efficient way to add a new pair key value to my existing nested dict. I am currently looping through the keys to do so. Here is an example:

>>> for k in tmp_dict.keys():
        tmp_dict[k].update({'C':1})

Lucas
  • 6,869
  • 5
  • 29
  • 44
armin
  • 591
  • 3
  • 10

1 Answers1

1

A simple method would be like so:

for key in tmp_dict:
    tmp_dict[key]['C']=1

Or, you could use dictionary comprehension, as sushanth suggested

tmp_dict = {k: {**v, 'C': 1} for k, v in timp_dict.items()}

You can read more about the asterisks (and why this works) here.

In terms of complexity, they are all O(N) time complexity (I think the dict comprehension maybe O(N^2)). So, your solution should have a relatively quick run time anyways.

KarmaPenny
  • 164
  • 1
  • 13
  • The first part is the fastest way. I believe the creation of a new dictionary outstrips the speed gains of the comprehension. – Marcel Wilson Apr 30 '21 at 20:27