How can you add entries, and retrieve, alter, or r

2019-04-17 11:53发布

I was working on a cool project I am doing in Python and I needed a way to do this without recursion because this would limit the size it could be by limiting the amount of times the loop could go through it (max recursion depth). The function needs to work on a nest dictionary of any size. How can I add entries, and retrieve, alter, or remove values from specific keys in any nested dictionary? I haven't found a good answer for this on SO because they all are either overly complex or use recursion.

2条回答
We Are One
2楼-- · 2019-04-17 12:34

I created this simple module that demonstrates this functionality that precisely does this. You just must know the keypath, per se. You can take out the demos and use it in any project by grabbing it from Github, as this is licensed with the MIT License. Enjoy!

It'd be interesting to see this benchmarked.

'''
MIT License

Copyright (c) 2019 Keith Cronin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''

d = {}
d['fruits'] = {}
d['fruits']['orange'] = {}
d['fruits']['orange']['price'] = 5.75

my_keystring = "fruits.orange.price"

def get_value(keystring, dictionary):
    amountkeys = keystring.count('.')+1
    lastfoundindex = 0
    counter = 0

    while counter < amountkeys:
            if counter == 0:
                    value = dictionary[keystring[lastfoundindex:keystring.find('.')]]

            elif counter == amountkeys - 1:
                    value = value[keystring[lastfoundindex:]]
                    break
            else:
                    value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]

            lastfoundindex = keystring.find('.',lastfoundindex)+1
            counter += 1

    return value

print(F"Demo get_value(): {get_value(my_keystring, d)}\nThis is the PRICE of ORANGE in FRUITS.")

def set_value(keystring, dictionary, new_value):
    amountkeys = keystring.count('.')+1
    lastfoundindex = 0
    counter = 0

    while counter < amountkeys:
            if counter == 0:
                    value = dictionary[keystring[lastfoundindex:keystring.find('.')]]

            elif counter == amountkeys - 1:
                    value[keystring[lastfoundindex:]] = new_value
                    break
            else:
                    value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]

            lastfoundindex = keystring.find('.',lastfoundindex)+1
            counter += 1

    value = new_value
    return value

print(F"Demo set_value(): {set_value(my_keystring, d, 1.25)}\nThis is the NEW PRICE of ORANGE in FRUITS!")

def del_entry(keystring, dictionary):
    amountkeys = keystring.count('.')+1
    lastfoundindex = 0
    counter = 0

    while counter < amountkeys:
            if counter == 0:
                    value = dictionary[keystring[lastfoundindex:keystring.find('.')]]

            elif counter == amountkeys - 1:
                    del value[keystring[lastfoundindex:]]
                    break
            else:
                    value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]

            lastfoundindex = keystring.find('.',lastfoundindex)+1
            counter += 1

del_entry('fruits.orange.price',d)
print(F"Demo del_entry(): fruits.orange.price is now {get_value('fruits.orange', d)}!")


def add_entry(keystring, dictionary, entry_name, entry_value = None):
    amountkeys = keystring.count('.')+1
    lastfoundindex = 0
    counter = 0

    while counter < amountkeys:
            if counter == 0:
                    value = dictionary[keystring[lastfoundindex:keystring.find('.')]]

            elif counter == amountkeys - 1:
                    value[keystring[lastfoundindex:]][entry_name] = entry_value
                    break
            else:
                    value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]

            lastfoundindex = keystring.find('.',lastfoundindex)+1
            counter += 1

add_entry('fruits.orange', d, 'in_stock', True)
print(F"Demo add_entry()! Added a new entry called in_stock to fruits.orange, it's value is: {get_value('fruits.orange.in_stock',d)}")
查看更多
冷血范
3楼-- · 2019-04-17 13:00

Well, you could also go another way:

d = {}
my_keystring = "fruits.orange.price"
d[my_keystring] = 5.75

print(F"Demo get value: {d[my_keystring]}\nThis is the PRICE of ORANGE in FRUITS.")

d[my_keystring] = 1.25
print(F"Demo set value: {d[my_keystring]}\nThis is the NEW PRICE of ORANGE in FRUITS!")

del d[my_keystring]
print(F"Demo del entry: fruits.orange.price is now {d.get(my_keystring)}!")

d['fruits.orange.in_stock'] = True
print(F"Demo add entry! Added a new entry called in_stock to fruits.orange, it's value is: {d['fruits.orange.in_stock']}")

Which yields

Demo get value: 5.75
This is the PRICE of ORANGE in FRUITS.
Demo set value: 1.25
This is the NEW PRICE of ORANGE in FRUITS!
Demo del entry: fruits.orange.price is now None!
Demo add entry! Added a new entry called in_stock to fruits.orange, it's value is: True
查看更多
登录 后发表回答