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.
},
"meta": {
"tags": "Tagged",
"page": "Page"
},
"404": {
"title": "404 Page Not Found",
"subtext_html": "Hello"
},
Hello there
How are you
Nice to meet you
Read more
The outcome im searching:
},
"meta": {
"tags": "Hello there",
"page": "How are you"
},
"404": {
"title": "Nice to meet you",
"subtext_html": "Read more"
},
Kind regards
CodePudding user response:
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'}}