Python Forum
Replace string in a nested Dictianory.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace string in a nested Dictianory.
#1
Hi everyone,

I've got a huge nested dict from a yaml call
with open('MyYamlFile.yml', 'r') as file:
	yml_test = yaml.safe_load(file)
I would like to do ~a
yml_test.replace('wrong','right')
But of course we can't call a .replace on a Dict... :/

So how could I change ALL string that are nested / embedded within the yml_test ?

Thanks.
[Image: NfRQr9R.jpg]
Reply
#2
Can write a own solution usually a recursive approach that would traverse the dictionary.
Or use a solution that dos this eg nested-lookup.
Test.
from nested_lookup import nested_lookup
from nested_lookup import nested_update

nested_dict = {
    'level1': {
        'level2a': {
            'level3a': {
                'value': 1
            },
            'level3b': {
                'value': 2
            }
        },
        'level2b': {
            'level3c': {
                'value3': 3
            }
        }
    }
}
>>> result = nested_update(nested_dict, key='value', value=99)
>>> result
{'level1': {'level2a': {'level3a': {'value': 99}, 'level3b': {'value': 99}},
            'level2b': {'level3c': {'value3': 3}}}}
>>> 
>>> result = nested_update(result, key='value3', value=['hello', 100])
>>> result
{'level1': {'level2a': {'level3a': {'value': 99}, 'level3b': {'value': 99}},
            'level2b': {'level3c': {'value3': ['hello', 100]}}}}
SpongeB0B likes this post
Reply
#3
Nice ! Thank you @snippsat
[Image: NfRQr9R.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 761 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  [split] Parse Nested JSON String in Python mmm07 4 1,521 Mar-28-2023, 06:07 PM
Last Post: snippsat
  Replace with upper(string) WJSwan 7 1,583 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  Find and Replace numbers in String giddyhead 2 1,222 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,102 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 5,008 Aug-07-2021, 08:16 AM
Last Post: perfringo
  How to replace on char with another in a string? korenron 3 2,346 Dec-03-2020, 07:37 AM
Last Post: korenron
  Replace string in many files in a folder metro17 8 5,585 Oct-16-2019, 06:46 PM
Last Post: ndc85430
  open, read and replace a string in a file Reims 0 1,804 Oct-02-2019, 01:30 PM
Last Post: Reims
  Read each line, replace string and save into a new file igormonteiro 2 3,260 Sep-15-2019, 01:24 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020