0

I'm generating a dict from a JSON file, and I want to append all the values that have the same beginning under one key. I don't really know how, I suppose that I should use something from re and tag everything that matched with the beginning?

Here's a sample of the JSON:

[{..."derived-missing_residues-mobi-2btp_A":{'stuffgoeshere'},'derived-missing_residues-mobi-6bcr_A':{'morestuffgoeshere'}}]

As you can see, they all share the 'derived-missing_residues-mobi-" part. It only changes at the end.

And the code that I have is really simple:

import json

dict_name = dict.fromkeys(['...','MISSING',])
with open("path\Json1.json") as f:
    data = json.loads(f.read())
    for  i in data: 
        if 'derived-missing_residues-mobi-' in i: #Here I should be using re, somehow.
            dict_name['MISSING']=(i['MISSING'])

something with re.findall(r'.*',derived-missing_residues-mobi-) could do the trick but I'm not really familiar with the library. Thanks in advance!

JuanMacD
  • 171
  • 7
  • Why not just `if i.startswith('derived-missing_residues-mobi-'):` ? – DeepSpace Jan 22 '21 at 19:18
  • This question is not really related to JSON. – VPfB Jan 22 '21 at 19:20
  • 3
    No don’t use `re` to attempt parsing JSON. Regular Expressions aren’t good for some basic things like matching quotes and escaped characters, and nested elements. Just use `json.loads()`to parse the json string to a list or dictionary then use normal Python list and dictionary access. – DisappointedByUnaccountableMod Jan 22 '21 at 19:21
  • Maybe there's a more efficient way to do it in a JSON, that's why I tagged it! – JuanMacD Jan 22 '21 at 19:21
  • @barny Not sure what you mean. They're already using `json.loads`. – superb rain Jan 22 '21 at 19:30
  • Cthulhu says no. – Z4-tier Jan 22 '21 at 19:32
  • @JuanMacD This task has little to do with json or regexps. What you need to do is traverse the hierarchy of dicts/lists and look for any keys that match. There are already [many answers on SO that show how to do that](https://stackoverflow.com/q/9807634/984421). – ekhumoro Jan 22 '21 at 19:37

0 Answers0