简体   繁体   English

如何使用 for 循环与 python 进行字典?

[英]How to dictionary with python using for loop?

I have the following python script (Some lines not present because not needed):我有以下 python 脚本(有些行不存在,因为不需要):

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

The output is the following: output如下:

[{'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:但是当我在使用数据之前去https://jsonlint.com/检查 JSON 结构是否有效时,我得到了错误:

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. PS:还有另一条线不是我创作的,虽然对我有用但不是真的。

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):它还在 JSON Lint 上向我返回了一个错误,这也对我没有帮助,因为我正在尝试构建这样的东西(在 JSON Lint 检查上通过 OK):

[{
    "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.再一次 -我真的很抱歉这个问题,我知道这一定是一个非常愚蠢的问题 - 但我不知道除了 StackOverflow 之外 go 去哪里,我是一名学生/实习生,没有前辈来帮助我在哪里我工作在。

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().我会使用 json 模块及其 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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