Skip to content

DictReader Example #9

@JulioPDX

Description

@JulioPDX

Hello All,

Chuck mentioned that you can use DictReader within csv to read the contents of the file. Here is an example of doing just that and the print out. I added this to the end of the l_04_csv_example.py file.

from rich import print
print("Test using DictReader")
my_list_of_dicts = list()
with open("l_00_inventory_back_to_csv.csv", newline="") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        my_list_of_dicts.append(row)
print(my_list_of_dicts)
Test using DictReader
[
    {
        'name': 'frodo-baggins',
        'hostname': 'frodo.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'frodo',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'sam-gamgee',
        'hostname': 'sam.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'sam',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'pippin-took',
        'hostname': 'pippin.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'pippin',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'merry-brandybuck',
        'hostname': 'merry.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'merry',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'gandalf',
        'hostname': 'gandalf.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'gandalf',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'aragorn',
        'hostname': 'aragorn.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'aragorn',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'legolas',
        'hostname': 'legolas.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'legolas',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'gimli',
        'hostname': 'gimli.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'gimli',
        'ssh-password': 'Admin_1234!'
    },
    {
        'name': 'boromir',
        'hostname': 'boromir.tallac.com',
        'ssh-port': '8181',
        'ssh-username': 'boromir',
        'ssh-password': 'Admin_1234!'
    }
]

Thanks again Chuck!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions