'Create a List of Dictionaries from a Text File
I have a text file that contains hostnames of devices:
fc-acc-v-a-1
fc-cor-r-a-1
fc-agg-r1
I need to create a list of dictionaries from the text file that would look like this:
[{'hostname': 'fc-acc-v-a-1', 'platform': ''},
{'hostname': 'fc-cor-r-a-1', 'platform': ''},
{'hostname': 'fc-agg-r1', 'platform': ''}]
So far this is what I have for the code:
with open("Devices.txt", "r") as devices:
keys = ["hostname", "platform"]
hosts = devices.read().splitlines()
device_dict = [dict(zip(keys, values)) for values in hosts]
print(device_dict)
However this isn't doing what I want it to do. Here's a sample of the output:
[{'hostname': 'f', 'platform': 'c'},
{'hostname': 'f', 'platform': 'c'},
{'hostname': 'f', 'platform': 'c'}]
I need it to assign each line in the text file as the value for the key hostname, and the value for platform can be blank for now. I plan to create functions using PySNMP to get the sysDescr OID from each hostname and that will become the platform key value for each device.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
