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

Ability to get just the key (not including the root part) from a diff'd dictionary where a changed value was found #340

Open
jm20122012 opened this issue Aug 18, 2022 · 1 comment

Comments

@jm20122012
Copy link

jm20122012 commented Aug 18, 2022

Describe the solution you'd like
There's probably a way to do what I'd like to do, but the documentation is very confusing, and I'm not seeing a way to do this.

What I'd like to do is diff two dictionaries, and instead of the report telling me "root['key']", I'd like to be able to get JUST the key where the change was found not including the "root" part.

What I'm trying to ultimately do is run a program to get the differences, then send those differences off to another program that will update a GUI based on the changes. But I would like to format the message that will be sent to the GUI like this:

changes = [

{"Device_1" : {"key_for_val_that_changed_1": {"old_value": "foo", "new_value": "bar"}}},

{"Device_2" : {"key_for_val_that_changed_2": {"old_value": "foo", "new_value": "bar"},
               "key_for_val_that_changed_3": {"old_value": "foo", "new_value": "bar"}}}

] 

To be more clear, if I had a diff result that gave me the following:

{'values_changed': {"root[1]['tx_data_rate']": {'new_value': '8192', 'old_value': '2048'}, "root[1]['rx_eb_no']": {'new_value': '9.6', 'old_value': '9.4'}, "root[2]['tx_center_freq']": {'new_value': '1250', 'old_value': '1220'}}}

How can I strip just the 'tx_data_rate' key out instead of "root[1]['tx_data_rate']"?

@BeebBenjamin
Copy link

BeebBenjamin commented Aug 19, 2022

I'm not associated with this repository, but I have the same problem. So I use regex in something like the code below:

import re

from typing import Pattern

keys_regex: Pattern = re.compile(r"(?<=\[)'?(.*?)'?(?=])")
key_matches = re.findall(keys_regex, "root[1]['tx_data_rate']")

print(key_matches)

You end up with a result like: ['1', 'tx_data_rate']

You just need to grab the keys from the differences object first, like list(differences.get('values_changed').keys()) then use the regex on each key to get the keys out of it, if you understand my meaning?

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

No branches or pull requests

2 participants