Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keys method with (dotted=True) gives multiplication of the same key #237

Open
aviveh21 opened this issue Dec 25, 2022 · 1 comment
Open
Labels

Comments

@aviveh21
Copy link

Bug of keys in Box:

When you use keys() method in a "dotted" situation, meaning we have a tree of keys in a Box, and you want to get the keys of a given node, one can notice that we get back a list of keys that are multiplicated if the value of a key is a list. (and the multiplication is by the lengh of the list)

For example:

 

b = Box({
"Animals" : {"Land_animals" : ["Lion", "Elephant"], "Sea_animals" : ["Dolphin", "Shark"]},
"Trees" : ["Palm_tree", "Coconut_tree"]
}, box_dots = True)

 

When you are using keys = b.keys(dotted = True) you get -

['Animals.Land_animals[0]',
'Animals.Land_animals[1]',
'Animals.Sea_animals[0]',
'Animals.Sea_animals[1]',
'Trees[0]',
'Trees[1]']

and we can see the multiple occurances of the keys (with indexes of their number of values), and the method len(keys) would have wrong answer - 6 instead of 3.

The output which I thought would be right is: ['Animals.Land_animals', 'Animals.Sea_animals', 'Trees']

 

A workaround is to add to the box this:

box_intact_types = (tuple,list)

so that lists wouldn't be converted, and than it works fine.

@cdgriffith
Copy link
Owner

This is actually working as intened to allow you to go recursivly through Box or BoxLists as well. For example:

from box import Box

b = Box({
"Animals" : {"Land_animals" : ["Lion", "Elephant"], "Sea_animals" : ["Dolphin", "Shark"]},
"Trees" : [{"name": "Palm_tree"}, {"name": "Coconut_tree"}]
}, box_dots = True)

print(b.keys(dotted=True))
#   ['Animals.Land_animals[0]', 'Animals.Land_animals[1]', 
#    'Animals.Sea_animals[0]', 'Animals.Sea_animals[1]', 'Trees[0].name', 'Trees[1].name']

for key in b.keys(dotted=True):
    print(b[key])

Shows:

Lion
Elephant
Dolphin
Shark
Palm_tree
Coconut_tree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants