python regex to get key value pair - python-regex

var abcConfig={
"assetsPublicPath":"https://abcd.cloudfront.net/"
}
var abcConfig1={
"assetsPublicPath1":"https://abcd.cloudfront.net/1"
}
I am looking for a regex which generates key value pair
[
abcConfig: {"assetsPublicPath": "https://abcd.cloudfront.net/"},
abcConfig1: {"assetsPublicPath1": "https://abcd.cloudfront.net/1"}
]

Using your sample, I came up with the following example code in Python:
import re
rs = r'var\s+(?P<key>.*)\s*=\s*(?P<val>\{\s*.*?\s*\})\s*'
m = re.finditer(rs, test)
for mm in m:
gd = mm.groupdict()
print(gd['key'], gd['val'])
This captures the key and value from the text into named groups, which get stored in the groupdict. You could then use these values to build your dictionary or do whatever you need to do.

Related

Can't figure how to stop dictionary keys from overwriting themselves

I'm trying to create a dictionary and my dictionary keys keep overwriting themselves. I don't understand how I can handle this issue.
Here's the script:
import MDAnalysis as mda
u = mda.Universe('rps5.prmtop', 'rps5.inpcrd')
ca = u.select_atoms('protein')
charges = ca.charges
atom_types = ca.names
resnames = ca.resnames
charge_dict = {}
for i in range(len(charges)):
#print(i+1 ,resnames[i], atom_types[i], charges[i])
charge_dict[resnames[i]] = {}
charge_dict[resnames[i]][atom_types[i]] = charges[i]
print(charge_dict)
The charges, atom_types and resnames are all lists, with the same number of elements.
I want my dictionary to look like this: charge_dict[resname][atom_types] = charges (charge_dict['MET']['CA'] = 0.32198, for example).
Could you please help me with this issue?
Without actually seeing a complete problem description, my guess is that your final result is that each charge_dict[name] is a dictionary with just one key. That's not because the keys "overwrite themselves". Your program overwrites them explicitly: charge_dict[resnames[i]] = {}.
What you want is to only reset the value for that key if it is not already set. You could easily do that by first testing if resnames[i] not in charge_dict:, but the Python standard library provides an even simpler mechanism: collections.defaultdict. A defaultdict is a dictionary with an associated default value creator. So you can do the following:
from collections import defaultdict
charge_dict = defaultdict(dict)
After that, you won't need to worry about initializing charge_dict[name] because a new dictionary will automatically spring into existence when the default value function (dict) is called.

Reading and writing to a dictionary dynamically

I am trying to read value from dictionary and then write to a different one.
The following works, but is hardcoded
this_application['bounces'] = {}
this_application['bounces']['month'] = {}
this_application['bounces']['month']['summary'] = {}
try:
got_value = application.ga_data['ga:bounces']['ga:month']['summary']['recent']
except:
got_value = ""
this_application['bounces']['month']['summary']['recent'] = got_value
What I want to do though, is pass in a from and to list (as I will have lots of these).
I was imagining the input would be something like this
{"ga_data": [{"from": "ga:bounces.ga:month.summary.recent", "to": "bounces.month.summary.recent"},{"from": "ga:sessions.ga:month.summary.recent", "to": "sessions.month.summary.recent"}]}
In which case it would do the above twice (with checking for existing dictionaries etc). I am fine on the checking etc., it is how to use the above that I am stuck on.
Any help would be appreciated
Thanks
You can use defaultdict but there are some special things to consider when doing it. If you read a value that does not exist it will add an empty value to the dict.
import collections
nested_dict = lambda: collections.defaultdict(nested_dict)
d = nested_dict()
d[1][2][3] = 'Hello, dictionary!'
print(d[2]) # I read the value and thus added the key to the dict
print(d[1][2][3]) # Prints Hello, dictionary!
print(d.keys()) # Shows that [1, 2] are keys
Credit To: How can I get Python to automatically create missing key/value pairs in a dictionary?

How to loop through a map and display only one row if there is matching values

I have a map with differnt keys and multiple values.If there is any matching job among different keys,I have to display only one row and grouping code values.
def data = ['Test1':[[name:'John',dob:'02/20/1970',job:'Testing',code:51],[name:'X',dob:'03/21/1974',job:'QA',code:52]],
'Test2':[name:'Michael',dob:'04/01/1973',job:'Testing',code:52]]
for (Map.Entry<String, List<String>> entry : data.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
values.eachWithIndex{itr,index->
println("key is:"+key);
println("itr values are:"+itr);
}
}
Expected Result : [job:Testing,code:[51,52]]
First flatten all the relevant maps, so whe just have a flat list of all of them, then basically the same as the others suggested: group by the job and just keep the codes (via the spread operator)
def data = ['Test1':[[name:'John',dob:'02/20/1970',job:'Testing',code:51],[name:'X',dob:'03/21/1974',job:'QA',code:52]], 'Test2':[name:'Michael',dob:'04/01/1973',job:'Testing',code:52]]
assert data.values().flatten().groupBy{it.job}.collectEntries{ [it.key, it.value*.code] } == [Testing: [51, 52], QA: [52]]
Note: the question will be changed according to the comments from the other answers.
Above code will give you the jobs and and their codes.
As of now, it's not clear, what the new expected output should be.
You can use the groovy's collection methods.
First you need to extract the lists, since you dont need the key of the top level element
def jobs = data.values()
Then you can use the groupBy method to group by the key "job"
def groupedJobs = jobs.groupBy { it.job }
The above code will produce the following result with your example
[Testing:[[name:John, dob:02/20/1970, job:Testing, code:51], [name:Michael, dob:04/01/1973, job:Testing, code:52]]]
Now you can get only the codes as values and do appropriate changes to make key as job by the following collect function
def result = groupedJobs.collect {key, value ->
[job: key, code: value.code]
}
The following code (which uses your sample data set):
def data = ['Test1':[name:'John', dob:'02/20/1970', job:'Testing', code:51],
'Test2':[name:'Michael', dob:'04/01/1973', job:'Testing', code:52]]
def matchFor = 'Testing'
def result = [job: matchFor, code: data.findResults { _, m ->
m.job == matchFor ? m.code : null
}]
println result
results in:
~> groovy solution.groovy
[job:Testing, code:[51, 52]]
~>
when run. It uses the groovy Map.findResults method to collect the codes from the matching jobs.

How to get the specific value from the data using python?

data = ['{"osc":{"version":"1.0"}}']
or
data = ['{"device":{"network":{"ipv4_dante":{"auto":"testing"}}}}']
From the code above, I only get random outputs, but I need to get the last value i.e "1.0" or "testing" and so on.
I always need to get the last value. How can I do it using python?
Dictionaries have no "last" element. Assuming your dictionary doesn't branch and you want the "deepest" element, this should work:
import json
data = ['{"device":{"network":{"ipv4_dante":{"auto":"testing"}}}}']
obj = json.loads(data[0])
while isinstance(obj, dict):
obj = obj[list(obj.keys())[0]]
print(obj)
This should work -
import ast
x = ast.literal_eval(data[0])
while(type(x)==dict):
key = x.keys()[0]
x = x.get(key)
print(x)

python 3.5: How to change the format of dictionary to be accepted by rest api

I am trying to build an input parameter which is a dictionary, but it's format is different in compare with normal dictionary,
what i already have is this
{"sort": {"-p1.m_visits_all"}}
and I am trying to change the format of the dictionary which is valid one in my rest query, the final format should be like this
{"sort": "{-p1.m_visits_all}"}
but I don't know how to do it. Any suggestions?
First, you can convert each dict value to a string with str(...).
Now your example would look like this:
{"sort": "{'-p1.m_visits_all'}"}
Next, you remove all single quotes (') in the values
. Now you have:
{"sort": '{-p1.m_visits_all}'}
Finally, you may convert it to JSON with json.dumps(), and you and up with:
'{"sort": "{-p1.m_visits_all}"}'
Here is a function that formats a dict and then returns a JSON string:
def format_for_api(params):
formatted = {}
for k, v in params.items():
params[k] = str(v).replace("'", "")
return json.dumps(formatted)
Or, using compressions:
def format_for_api(params):
return json.dumps({k: str(v).replace("'", "") for k, v in params.items()})
Happy coding :)

Resources