Python Forum

Full Version: How can I organize my code according to output that I want
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone. I have the code below.

import json

with open('data6.json') as f:
    data = json.load(f)
    for item in data:
        for dct in item:
            print('------------------')
            for key in ['Manufacturer', 'Name']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")
            for key in ['IPAddress']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")
            for key in ['UserName']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")


My output is like:
------------------
Manufacturer --> VMware, Inc.
Name --> DC01
IPAddress --> Key Not Present
UserName --> Key Not Present
------------------
Manufacturer --> Key Not Present
Name --> Key Not Present
IPAddress --> ['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
UserName --> Key Not Present
------------------
Manufacturer --> Key Not Present
Name --> DC01
IPAddress --> Key Not Present
UserName --> None
But i want an Output like:


Manufacturer --> VMware, Inc.
Name --> DC01
IPAddress --> ['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
UserName --> DC01
How should I organize my code for such an output?
(Mar-11-2022, 08:24 AM)ilknurg Wrote: [ -> ]How should I organize my code for such an output?

We have no idea what is the structure of data6.json file so how could we know?

Regardless of that - why use three for loops?

for dct in item:
            print('------------------')
            for key in ['Manufacturer', 'Name']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")
            for key in ['IPAddress']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")
            for key in ['UserName']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}")

# same functionality:

for dict_ in record:
    for key in ['Manufacturer', 'Name', 'IPAddress', 'UserName']:
        print(f"{key} --> {dict_.get(key, 'Key Not Present')}")