I have a file containing mac_address, RSSI value and time value; I want create a dictionary where the keys are the mac_address and the values are the RSSI and time. How can I do this?
The file is formatted as this:
6E:C6:F8:89:AE:64 -71dBm 10:18:25
C4:A5:DF:24:05:7E -45dBm 10:18:26
B0:6E:BF:1F:5E:A1 -27dBm 10:18:48
But I can have more than 3 row sometimes
CodePudding user response:
You can use a dictionary comprehension:
with open('file.txt') as f:
mac_dic = {k:tuple(v) for k,*v in map(str.split, f.readlines())}
output:
>>> mac_dic
{'6E:C6:F8:89:AE:64': ('-71dBm', '10:18:25'),
'C4:A5:DF:24:05:7E': ('-45dBm', '10:18:26'),
'B0:6E:BF:1F:5E:A1': ('-27dBm', '10:18:48')}
Here is an alternative format:
with open('file.txt') as f:
mac_dic = {k:dict(zip(['RSSI', 'time'], v))
for k,*v in map(str.split, f.readlines())}
>>> mac_dic
{'6E:C6:F8:89:AE:64': {'RSSI': '-71dBm', 'time': '10:18:25'},
'C4:A5:DF:24:05:7E': {'RSSI': '-45dBm', 'time': '10:18:26'},
'B0:6E:BF:1F:5E:A1': {'RSSI': '-27dBm', 'time': '10:18:48'}}
CodePudding user response:
Using type hints and NamedTuple
from typing import NamedTuple,Dict
class RSSI(NamedTuple):
rssi: str
time:str
mac = str
data: Dict[mac,RSSI] = dict()
with open('test.txt') as f:
for line in f:
mac,rssi,time = line.split()
data[mac] = RSSI(rssi,time)
print(data)
output
{'6E:C6:F8:89:AE:64': RSSI(rssi='-71dBm', time='10:18:25'), 'C4:A5:DF:24:05:7E': RSSI(rssi='-45dBm', time='10:18:26'), 'B0:6E:BF:1F:5E:A1': RSSI(rssi='-27dBm', time='10:18:48')}