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

标签 python dictionary

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

$ 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)        

关于python - 在 Python 中将字符串拆分为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172752/

相关文章:

python - 检查连接是否已使用 Twisted 关闭

python - 多线程 GUI 编程需求说明

Python 的 'with' 语句与 'with .. as'

python - 堆积面积图 Seaborn 独特值 X 轴

python:迭代不断变化的字典

Python:是否可以在不逐个单元格迭代的情况下删除一系列excel单元格中的值?

json - 最好将数组,集合或字典用于大量项目?

java - 需要根据值(登录时间)对自定义 HashMap 进行排序

python - 使用第二个元素从元组列表创建字典

Python如何按字典键对嵌套字典列表进行排序?