Awin
Awin

Reputation: 91

Parsing string through dictionary

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.

Upvotes: 0

Views: 61

Answers (3)

backtrack
backtrack

Reputation: 8144

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.

Upvotes: 0

ricekab
ricekab

Reputation: 650

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)

Upvotes: 1

Abdullah Tamimi
Abdullah Tamimi

Reputation: 11

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]

Upvotes: 1

Related Questions