Home > Mobile >  Adding multiple new key-value pairs to a nested dictionary
Adding multiple new key-value pairs to a nested dictionary

Time:02-16

I am new to python and I am trying to add key-value pairs to a nested dictionary. I tried a few approaches but I am not able to do it properly. This is the code that I have written:

dict1 = {}
dict1['name'] = {'domain': "something"}
i=0
while i < 10:
    new = 'route' str(i)
    dict1['name']['routes'] = {new: {'bit_value': i}}
    i = i 1
print(dict1)

This is the output I am getting:

{'name': {'domain': 'something', 'routes': {'route9': {'bit_value': 9}}}}

This is the kind of output that I want:

{'name': {'domain': 'something', 'routes': {'route1': {'bit_value': 1}, 'route2': {'bit_value': 2}, 'route3': {'bit_value': 3}, 'route4': {'bit_value': 4} ...}}}

I tried using this version as well, but it throws a Keyerror:

import collections

dict1 = collections.defaultdict(dict)
dict1['name'] = {'domain': "something"}
i = 0
while i < 10:
    new = 'route' str(i)
    dict1['name']['routes'][new] =  {'bit_value': i}
    i = i 1
print(dict1)

Error message:

dict1['name']['routes'][new] =  {'bit_value': i}
KeyError: 'routes'

It would be nice if this problem can be solved without changing into a for loop as the while loop will make it easier for me to integrate this with rest of the code that I have written. I would really appreciate if someone can help me.

CodePudding user response:

First create the routes sub-dictionary, then insert items.

import collections

dict1 = collections.defaultdict(dict)
dict1['name'] = {'domain': "something"}
i = 0
##########
dict1['name']['routes'] = {} 
##########
while i < 10:
    new = 'route' str(i)
    dict1['name']['routes'][new] =  {'bit_value': i}
    i = i 1

print(dict1)

CodePudding user response:

In your original solution, dict1['name']['routes'] is replaced with a new dictionary with only 1 key every time.

In your alternative version, dict1 is a defaultdict. So you can access e.g. dict1['randomkey'] without initializing it, but dict1['name'] or dict1['name']['routes'] is not a defaultdict. defaultdict(dict) means the values are normal dictionaries. If you need the values to be defaultdict as well, you can do defaultdict(defaultdict(dict))

But that's not what you want. You don't actually need to deal with default key values. You only need to initialize dict1['name']['routes'] once to a normal dictionary:

dict1 = {'name': {'domain': 'something', 'routes': {}}}
for i in range(10):
    dict1['name']['routes'][f'route{i}'] = {'bit_value': i}

A few bonus tips

  1. Don't mix 'string' with "string"
  2. Use for i in range(10) instead of a while loop. Much simpler and easier to read
  3. Use f-string to format string f'route{i}'

As a matter of fact, your code can also be achieved with dictionary comprehension

dict1 = {'name': {'domain': 'something'}}
dict1['name']['routes'] = {f'route{i}': {'bit_value': i} for i in range(10)}
  • Related