Search code examples
pythonlistdictionaryreplacenested

python - replace ALL values in a nested dictionary


I would like to replace all VALUES in a nested dictionary with values from a list. Been searching for hours and can't seem to find a solution.

So I read values from a txt file and puts them in a list, then I want to replace all the dict values with the values from the list.

This would work well since all items in the list is the same amount of values in the nested dict.

This is my code so far:

def print_hi(name):

     
    file = open("list.txt")
    list = file.read()
    file.close()

    newlist = list.split("\n")

    file = open("lang.json")
    jsonString = file.read()
    file.close()

    jsonObject = json.loads(jsonString)

    for key, value in jsonObject.items():
     jsonObject[key] = newlist[]
     print(jsonObject)




if __name__ == '__main__':
    print_hi('PyCharm')

Example how my .json and .txt looks like.

    {
  "general": {
    "accessibility": {
      "skip_to_content": "Skip to content",
      "close_modal": "Close (esc)",
      "close": "Close",
      "learn_more": "Learn more"
    },

Hello there
How are you 
Nice to meet you
Read more

The outcome im searching:

  "general": {
    "accessibility": {
      "skip_to_content": "Hello there",
      "close_modal": "How are you",
      "close": "Nice to meet you",
      "learn_more": "Read more"
    },

Kind regards


Solution

  • Since it's s liner assignment of values we can iterate through the JSON object and replace its values. Like this

    for k in jsonObject:
        for sub_k in jsonObject[k]:
            try:
               jsonObject[k][sub_k] = new_list.pop(0)
            except IndexError:
                print('List empty')
    
    print(jsonObject)
    {'meta': {'tags': 'Hello there', 'page': 'How are you '},
     '404': {'title': 'Nice to meet you', 'subtext_html': 'Read more'}}