[英]python string retrieve the value
Can some one please help me how to get the Value
for Key: 'labelnumber'
from string below?有人可以帮我如何从下面的字符串中获取
Key: 'labelnumber'
的Value
吗?
Tried json manipulation and eval but no luck.尝试了 json 操作和评估,但没有运气。
{'Value': 'infotech', 'Key': 'company'},{'Value': 'printing', 'Key': 'LineofBusiness'},{'Value': 'Non-Prod', 'Key': 'Environment'},{'Value': '1234-5623', 'Key': 'labelnumber'},{'Value': 'globalinfra', 'Key': 'ApplicationName'}
I need to get the value of "labelnumber" key which is "1234-5623"我需要获取“labelnumber”键的值,即“1234-5623”
This string comes from a dictionary该字符串来自字典
d1 = {'Name': 'Maintags', 'Type': 'String', 'Value': "{'Value': 'infotech', 'Key': 'company'},{'Value': 'printing', 'Key': 'LineofBusiness'},{'Value': 'Non-Prod', 'Key': 'Environment'},{'Value': '1234-5623', 'Key': 'labelnumber'},{'Value': 'globalinfra', 'Key': 'ApplicationName'}"}
>>>print(d1)
{'Name': 'Maintags', 'Type': 'String', 'Value': "{'Value': 'infotech', 'Key': 'company'},{'Value': 'printing', 'Key': 'LineofBusiness'},{'Value': 'Non-Prod', 'Key': 'Environment'},{'Value': '1234-5623', 'Key': 'labelnumber'},{'Value': 'globalinfra', 'Key': 'ApplicationName'}"}
>>>print(type(d1))
<class 'dict'>
>>>print(d1["Value"])
{'Value': 'infotech', 'Key': 'company'},{'Value': 'printing', 'Key': 'LineofBusiness'},{'Value': 'Non-Prod', 'Key': 'Environment'},{'Value': '1234-5623', 'Key': 'labelnumber'},{'Value': 'globalinfra', 'Key': 'ApplicationName'}
d1 = {'Name': 'Maintags', 'Type': 'String', 'Value': "{'Value': 'infotech', 'Key': 'company'},{'Value': 'printing', 'Key': 'LineofBusiness'},{'Value': 'Non-Prod', 'Key': 'Environment'},{'Value': '1234-5623', 'Key': 'labelnumber'},{'Value': 'globalinfra', 'Key': 'ApplicationName'}"}
my_values_dict = {d['Key']:d['Value'] for d in eval(d1['Value'])}
print(my_values_dict['labelnumber'])
output: 1234-5623
output:
1234-5623
Use eval() to get a tuple of dictionaries, loop through it to turn it in a single dictionary, access the key you need.使用 eval() 获取字典元组,循环遍历它以将其转换为单个字典,访问所需的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.