chuckablack / python-52-weeks

repository for teaching python
MIT License
107 stars 76 forks source link

DictReader Example #9

Open JulioPDX opened 3 years ago

JulioPDX commented 3 years ago

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!

chuckablack commented 3 years ago

Thanks Julio! I was just too lazy to do that myself. :-)

Which I discovered just this week, as I'm doing the code for Flask, kind of a mini-quokka, and wanted to read in YAML, JSON, and CSV via a REST API, and wanted the CSV to be Dict-based, but saw that I hadn't used DictReader (only DictWriter) in the lesson. So, I wrote a DictReader example, but it is just in the Flask module.

So thanks for that code that does it in the CSV example area!

JulioPDX commented 3 years ago

Anytime and keep it up! Great resource for network engineers getting into Python.