简体   繁体   English

在python中如何将字符串转换为字典以检索特定值

[英]In python how do I convert string to dictionary to retrieve a particular value

One function returns below String s : s = 'Power On Enabled: On\\nsignalStrength: -050\\nip address: 192.168.75.123\\n' 一个函数在String s下面返回:s ='Power On Enabled:On \\ nsignalStrength:-050 ​​\\ nip address:192.168.75.123 \\ n'

I want to read the value of ip address in above string s. 我想读取上面字符串s中的ip address的值。 Used below code : /* Code */ 在下面的代码中使用:/ *代码* /

s = 'Power On Enabled: On\nsignalStrength: -050\nip address: 
192.168.75.123\n' 

ipdict = {}
newstr = s.replace("\n",",")
newdict = ipdict.update(newstr)
ip = newdict.get('ip address')
print ip

Got below Error : "dictionary update sequence element #0 has length 1; 2 is required" 出现以下错误:“字典更新序列元素#0的长度为1;必须为2”

s = 'Power On Enabled: On\nsignalStrength: -050\nip address: 192.168.75.123\n'
s = s.strip().split("\n")
d = {}
for i in s:
    key, val = i.split(":")
    d[key] = val.strip()

print d
print d["ip address"]

Output: 输出:

{'signalStrength': '-050', 'Power On Enabled': 'On', 'ip address': '192.168.75.123'}

 192.168.75.123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM