简体   繁体   中英

How to dictionary with python using for loop?

I have the following python script (Some lines not present because not needed):

aps = c.get_aps()
ap_names = [{'IP':ap['ip'], 'Name':ap['name'], 'MAC':ap['mac']} for ap in aps]

The output is the following:

[{'IP': '192.168.30.19', 'Name': 'Antenna #1', 'MAC': '44:d9:e7:be:01:e8'},
{'IP': '192.168.30.24', 'Name': 'Antenna #2, 'MAC': '44:d9:e7:d2:64:1e'}]

But when i went to https://jsonlint.com/ to check if the JSON structure is valid before using the data i got the error:

Error: Parse error on line 1:
    [{          'IP': '192.168.30.19
------------^
Expecting 'STRING', '}', got 'undefined

I know this is a newbie question and i am sorry. I'm a beginner using this, so please, can someone help me a little bit?

PS: There was another line that was not made by me, which kind of worked but not really for me.

ap_names_old = dict([(ap['mac'], ap.get('name')) for ap in aps])

This outputs:

{'44:d9:e7:be:01:e8': 'Antenna #1', '44:d9:e7:d2:64:1e': 'Antenna #2'}

It also returned me a error on JSON Lint and also this doesnt help me at all since i'm trying to build something like this (Which pass OK on JSON Lint check):

[{
    "ip": "192.168.1.1",
    "name": "Antenna #1",
    "mac": "xx:xx:xx:xx"
}, {
    "ip": "192.168.1.2",
    "name": "Antenna #2",
    "mac": "xx:xx:xx:xx"
}]

Again - I am really sorry for this question, i understand this must be a very dumb thing to ask - But i do not know where to go besides StackOverflow, i'm a student/trainnee and do not have a senior to help me where i work at.

Thanks in advance. I really appreciate any tips, guides, documentations, etc, since i dont mind reading thousands of pages to get this done!

I would use json module and its function json.dumps().

import json
a = [dict({'IP': '192.168.30.19', 'Name': 'Antenna #1', 'MAC': '44:d9:e7:be:01:e8'}), dict({'IP': '192.168.30.24', 'Name': 'Antenna #2', 'MAC': '44:d9:e7:d2:64:1e'})]
print(a)  # output in jsonlint gives your error
print(json.dumps(a))  # now correct in jsonlint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM