Home > Software design >  Create a List of Dictionaries from a Text File
Create a List of Dictionaries from a Text File

Time:05-19

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.

CodePudding user response:

The platform doesn't come from the file, you should just hard-code it as an empty string. There's no need to use zip() since you don't have a list of keys and values.

device_list = [{'hostname': host, 'platform': ''} for host in hosts]
  • Related