Adding a new key to a nested dictionary in python

JSON:

{'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}

I am trying to add another dictionary this list, like this:

dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}
length = len(dict['result'])
print(length)

data_dict['results'][length+1] = [new_result]

I keep getting:

dict['result'][length+1] = [new_result]
IndexError: list assignment index out of range
1 Like

I cannot completely understand your question.

###If you want to simply add a new key to a dictionary:
Simply, use [‘your-desired-key’] to add a new key to the dictionary with its value.

dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}
new_result = [{'new_key1':'new_value1','new_key2':'new_value2'}, {'new_key1':'value3','new_key2':'value4'}]

# assign 'new_result' as a key
dict['new_result'] = new_result
dict

Output

{'new_result': [{'new_key1': 'new_value1', 'new_key2': 'new_value2'},
  {'new_key1': 'value3', 'new_key2': 'value4'}],
 'result': [{'key1': 'value1', 'key2': 'value2'},
  {'key1': 'value3', 'key2': 'value4'}]}

###If you want to add a new list item to a value in the dictionary:
You cannot use [ ] to insert an item to a list. That’s just for update.You need to use Python List append() method.

dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}
new_result = {'new_key1':'new_value1','new_key2':'new_value'}

# use append() to add new_result to list
dict['result'].append(new_result)
dict

Output

{'result': [{'key1': 'value1', 'key2': 'value2'},
  {'key1': 'value3', 'key2': 'value4'},
  {'new_key1': 'new_value1', 'new_key2': 'new_value'}]}
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.