Splitting String to dictionary in Python

Viewed 89

I would like to split the string to dictionary. String is taken by using

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

and my result is

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

The goal is creating dictionary where key is MAC address and value is rssi value

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

I tried a lot of replace function to replace these Strings to empty Strings:

  • hci0 dev_found:
  • type
  • LE
  • Random
  • rssi

But it must be cleaner and better way to do this dictionary and I do not see this solution.

Any ideas?

4 Answers

If every line has the same construction then you can use split() to split text into lines and later to split every line into "words" which you can use to create element in dictionary:

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)        

You can use re.findall with regex lookaheads and lookbehinds:

import re
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([re.findall('(?<=dev_found:\s)[A-Z\d:]+|[\-\d]+(?=\sflags)', i) for i in filter(None, s.split('\n'))])

Output:

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

Because the columns are separated by spaces, you can use the split method:

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"""

sdic = {}

for line in s.split('\n'):
    column = line.split(' ')
    sdic[column[2]] = column[7]

print(sdic)

Input: a file with given lines

import re
d = dict()
c1 = re.compile("((\d|\w){1,2}:){5}(\d|\w){1,2}")
c2 = re.compile(r"(-\d{2}) flags")
with open("your_saved_lines.txt") as fh:
  for l in fh.readlines():
    m1 = c1.search(l)
    m2 = c2.search(l) or "NA"
    if m1:
      d[m1.group()] = m2.group(1)
print(d)

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

Related