deepdiff icon indicating copy to clipboard operation
deepdiff copied to clipboard

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

Open jm20122012 opened this issue 3 years ago • 1 comments

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']"?

jm20122012 avatar Aug 18 '22 22:08 jm20122012

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?

BeebBenjamin avatar Aug 19 '22 16:08 BeebBenjamin