Behaviour of dictionary.append in python
我正在编写一些我的最高目标是以JSON格式提供一些信息的代码。我想这样显示服务器名和服务器URL:(我的目标不是漂亮的打印,但我只是这样显示,所以更明显)
1 2 3 4 5 6 | { "server": [ {"name" :"some_server_name","url" :"some_server_url" } {"name" :"another_server_name","url" :"another_server_url" } ] } |
我现在有两个列表,一个是服务器名,另一个是服务器URL。我迭代这些名称,然后访问匹配的URL。完成之后,我想把它附加到字典中。当我拿到这本词典时。我想把这个附加到我的json_dict中,我创建了这个dict,因为我还有另外两个列表要在我的json信息中显示。(可以忽略RDP和CERT,因为它们已经正确显示)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def build_dict(server_name, server_url, rdp, cert): json_dict = defaultdict(list) server_dict = {} if server_name and server_url: for i, iter_name in enumerate(server_name): server_dict.update( name = iter_name, url = server_url[i] ) json_dict['server'].append(server_dict) if rdp: for iter_rdp in rdp: json_dict['config'].append(iter_rdp) if cert: for iter_cert in cert: json_dict['cert'].append(iter_cert) return json_dict |
我的服务器名称列表中的条目:
[u'123name', u'qwer123']
以及我的服务器URL列表中的条目:
[u'123url', u'qwer123']
不幸的是,最终输出如下:
1 2 3 4 5 6 7 | {"cert": ["123url","123123","123123123"], "config": ["123rdp","123123","123123123"], "server": [ {"url":"qwer123","name":"qwer123"}, {"url":"qwer123","name":"qwer123"} ] } |
您可以忽略cert和config,因为它已经按预期工作了。我只是不明白为什么我有:
1 2 | {"url":"qwer123","name":"qwer123"}, {"url":"qwer123","name":"qwer123"} |
而不是:
1 2 | {"url":"123name","name":"123url"}, {"url":"qwer123","name":"qwer123"} |
作为输出。
如乔纳斯哈普所说,你的
1 2 3 4 | if server_name and server_url: for i, iter_name in enumerate(server_name): server_dict = dict( name = iter_name, url = server_url[i] ) json_dict['server'].append(server_dict) |