Skip to main content
 首页 » 编程设计

python之在 Python 中将字符串拆分为字典

2024年11月01日24insus

我想把字符串拆分成字典。字符串是通过使用

$ sudo btmgmt find |grep rssi |sort -n |uniq -w 33 

我的结果是

hci0 dev_found: 40:43:42:B3:71:11 type LE Random rssi -53 flags 0x0000  
hci0 dev_found: 44:DA:5F:EA:C6:CF type LE Random rssi -78 flags 0x0000 

目标是创建字典,其中键是 MAC 地址,值是 rssi 值

dict = { 
    "40:43:42:B3:71:11": "-53 ", 
    "44:DA:5F:EA:C6:CF": "-78", 
   } 

我尝试了很多替换函数来将这些字符串替换为空字符串:

  • hci0 dev_found:
  • 输入
  • 乐
  • 随机
  • rssi

但这本词典必须是更干净、更好的方法,我没有看到这个解决方案。

有什么想法吗?

请您参考如下方法:

如果每一行都具有相同的结构,那么您可以使用 split() 将文本拆分为多行,然后将每一行拆分为可用于在字典中创建元素的“单词”:

s = """ 
hci0 dev_found: 40:43:42:B3:71:11 type LE Random rssi -53 flags 0x0000  
hci0 dev_found: 44:DA:5F:EA:C6:CF type LE Random rssi -78 flags 0x0000 
""" 
 
d = dict() 
 
for line in s.split('\n'): 
    line = line.strip() # clear spaces and enters 
    if line: # skip empty lines 
        words = line.split(' ') 
        d[words[2]] = words[7] 
 
print(d)