I am wondering if there is any way to exchange key variables with value variables.
That means if i have
Obj1.val1 : request.label1,
Obj1.val2 : request.label2
Then is there any tool or python script that can convert above code to
request.label1 : Obj1.val1,
request.label2 : Obj1.val2
I tried converting it to string (copied the code and pasted inside double codes ) then split using space and : delimeter but as space is uneven between the data i was not able to get desired result
CodePudding user response:
If you have a dictionary with one value per key, e.g.
obj = {
1: 4,
2: 6,
3: 8,
}
Use the following dictionary comprehension (in python) to flip them:
flipped = {v: k for k, v in obj.items()}
>>> flipped = {v: k for k, v in obj.items()}
>>> flipped
{4: 1, 6: 2, 8: 3}
>>>
CodePudding user response:
If the values are already defined in a python dictionary, you can just loop over the dictionary and switch the key, value with value, key:
dict = {"key": "val", "key2": "val2"}
dict2 = {}
for k, v in dict.items():
dict2[v] = k
print(dict2)
# {"val": "key", "val2": "key2"}