ab='TS_Automation=Manual;TS_Method=Test;TS_Priority=1;TS_Tested_By=rjrjjn;TS_Written_By=SUN;TS_Review_done=No;TS_Regression=No;'
a={'TS_Automation'='Automated',TS_Tested_By='qz9ghv','TS_Review_done'='yes'}
I have a string and a dictionary ,Now i have to change the value in string based on the keys of dictionary.If the keys are not there subsequent value need to be removed.As TS_Method is not there in dictionary so need to be removed from the string ab.
Am I correct in understanding that you don't want to keep key-value pairs in the string if they don't occur in the dictionary? If that's the case, you can simply parse the dictionary to that particular string format. In your case it's simply in the form key=value; for each entry in the dictionary:
ab = ''
for key, value in a.items():
ab += "{}={};".format(key, value)
You would have to create a new string.
I would do it by using the find method using dictionary key/values for the search.
If the value being searched for does exist, I would append to a new string
s=''
for val in a:
word=val+'='+a[val]
wordLen=len(word)
x=ab.find(word)
if x != -1:
s+=ab[x:wordLen]
myvalue = ''
for k,v in a.items()
myvalue = myvalue+"{}={};".format(key, value)
ab = myvalue
just convert the dict to desired formated string and use it. There is no need for you to remove the key as your requirement is to use the dict as it is in string format.
Related
I need to select specific columns from a python dictionary using json.dumps().
Eg.
dict={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
r=json.dumps(Only want "Bike":Yamaha","Car":"Jaguar")
Note: Cannot store the same into other dictionary and use it. As I want to use First K,V pair as well in my code.
Create a new dictionary and dump that.
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
r = json.dumps({"Bike": d["Bike"], "Car": d["Car"]})
If you have a list of all the keys you want to keep, you can use a dictionary comprehension:
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
keep = ['Bike', 'Car']
r = json.dumps({key, d[key] for key in keep})
If you have a list of the keys you want to omit, you can also use a dictionary comprehension
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
skip = ['Greet']
r = json.dumps({key, val for key, val in d.items() if key not in skip})
BTW, don't use dict as a variable name, it's already the name of a built-in function/class.
final = list(mydict.items())[1:] #extra key:value tuple list slice of the portion you need
r=json.dumps(dict(final)) #cast to dictionary and dump
Output
{"Bike": "Yamaha", "Car": "Jaguar"}
I have a code which uses a dict to create a bunch of key-value pairs.
The no. of key-value pairs is undefined and not fixed. In one iteration, it can have 2 key value, in another it can 4 or 5.
The way I am doing is I currently use an empty dict
like
cost_dict = {}
Now when a regular expression pattern is found in a text string then I extract part of those text as key value pairs and populate the above dict with it.
However wherever the pattern is not found, I am trying to catch that exception of AttributeError and then in that specific case I want this above dict to be assigned like null or blank value.
So like
cost_dict ={}
try:
cost_breakdown = re.search(regex, output).group()
except AttributeError:
cost_dict =' ' # this part I am not sure how to do
... (if pattern matches extract the text and populate the above dict as key-value)
But I am not sure how to assign null or blank value to this dict then as above obviously creates a string variable cost_dict and does not assign it to the above defined empty dict.
I have a dictionary which looks like this:
dictionary={
"ABC-6m-RF-200605-1352": "s3://blabla1.com",
"ABC-3m-RF-200605-1352": "s3://blabla2.com",
"DEF-6m-RF-200605-1352": "s3://blabla3.com"
}
Now, I want to do a matching which takes input such as helper="ABC-6m" and tries to match this string to the key of the dictionary and returns the key (not the value)!
My code currently looks like this but it is not robust, i.e. sometimes it works and sometimes it does not:
dictionary_scan = dict((el, el[:7]) for el in dictionary)
#swapping key and value
dictionary_scan = dict((v, k) for k, v in dictionary.items())
#concat string components in helper variable
helper = 'ABC'+'-'+'6m'
out=list(value for key, value in dictionary_scan.items() if helper in key)
The expected output is: 'ABC-6m-RF-200605-1352'. Sometimes this works in my code but sometimes it does not. Is there a better and more robust way to do this?
If you make a dictionary that maps prefixes to full keys, you'll only be able to get one key with a given prefix.
If there can be multiple keys that start with helper, you need to check them all with an ordinary list comprehension.
out = [key for key in dictionary if key.startswith(helper)]
I am new to Python and working on revising some existing code.
There is a JSON string coming into a Python function that looks like this:
{"criteria": {"modelName":"='ALL'", "modelName": "='NEW'","fields":"*"}}
Right now it appears a dictionary is being used to create a string:
crit=data['criteria']
for crit_key in crit
crit_val = crit[crit_key]
sql+ = sql+= ' and ' + crit_key + crit_val
When the sql string is printed, only the last 'modelName' appears. It seems like a dictionary is being used as modelName is a key so the second modelName overwrites the first? I want the "sql" string in the end to contain both modelNames.
edited because of OP comments
Well, if you can't update your JSON and have to deal with.
You can make something like:
data = '{"criteria": {"modelName":"=\'ALL\'", "modelName": "=\'NEW\'","fields":"*"}}'
import json
def dict_raise_on_duplicates(ordered_pairs):
d = {}
duplicated = []
for k, v in ordered_pairs:
if k in d:
if k not in duplicated:
duplicated.append(k)
d[k] = [d[k]] + [v]
else:
d[k].append(v)
else:
d[k] = v
return d
print json.loads(data, object_pairs_hook=dict_raise_on_duplicates)
In this example, data is the JSON string with duplicated keys.
According to json.loads allows duplicate keys in a dictionary, overwriting the first value I just force json.load to handle duplicate keys.
If a duplicated key is spotted, it will create a new list containing current key data and add new value.
After, it will only append news values in created list.
Output:
{u'criteria': {u'fields': u'*', u'modelName': [u"='ALL'", u"='NEW'"]}}
You will have to update your code anyway, but you now can handle it.
In the below Python Code, am dynamically create Lists.
g['quest_{0}'.format(random(x))] = []
where random(x) is a random number, how to print the List(get the name of the dynamically created List name?)
To get a list of all the keys of your dictionary :
list(g.keys())
There is nothing different with a regular dictionary because you generate the key dynamically.
Note that you can also put any type of hashable object as a key, such as a tuple :
g[('quest', random(x))] = []
Which will let you get a list of all your quest numbers easily :
[number for tag, number in g.keys() if tag == "quest"]
With this technic, you can actually loop through the tag ('quest'), the number and the value in one loop :
for (tag, number), value in g.items():
# do somthing
Unpacking is your best friend in Python.
You can iterate over the g dictionary with a for loop, like this
for key, value in g.items():
print key, value
This will print all the keys and their corresponding lists.