我想知道如何静态初始化词典列表 - 如下所示:
最初,我有一个这样的清单:
consumers = ['aserver.foo.com','anotherserver.foo.com',
'thirdserver.foo.com','lastserver.foo.com']
但是我希望有一个我可以这样解决的结构:
consumers = [
'aserver'{
'hostname'='aserver.foo.com',
'binddn'=masterbinddn,
'bindpw'=masterbindpw
},
'anotherserver'{
'hostname'='anotherserver.foo.com',
'binddn'=masterbinddn,
'bindpw'=masterbindpw
},
'athirdserver'{
'hostname'='athirdserver.foo.com',
'binddn'=targetbinddn,
'bindpw'=targetbindpw
},
'lastserver'{
'hostname'='lastserver.foo.com',
'binddn'=targetbinddn,
'bindpw'=targetbindpw
}
]
这个想法是我可以做的事情:
for server in consumers:
do_something_to_server(server['hostname'], server['binddn'], server['bindpw'])
我是在咆哮错误的树,还是只是遗漏了一些基本的东西?
答案 0 :(得分:5)
以下内容将创建一个词典列表:
consumers = [
{
'hostname': 'aserver.foo.com',
'binddn': masterbinddn,
'bindpw': masterbindpw
},
{
'hostname': 'anotherserver.foo.com',
'binddn': masterbinddn,
'bindpw': masterbindpw
},
{
'hostname': 'athirdserver.foo.com',
'binddn': targetbinddn,
'bindpw': targetbindpw
},
{
'hostname': 'lastserver.foo.com',
'binddn': targetbinddn,
'bindpw': targetbindpw
},
]
然后你可以像这样迭代它:
for server in consumers:
do_something_to_server(server['hostname'], server['binddn'], server['bindpw'])
答案 1 :(得分:1)
采取你的结构:
consumers = {
'aserver': {
'hostname':'aserver.foo.com',
'binddn':masterbinddn,
'bindpw':masterbindpw
},
'anotherserver': {
'hostname':'anotherserver.foo.com',
'binddn':masterbinddn,
'bindpw':masterbindpw
},
'athirdserver': {
'hostname':'athirdserver.foo.com',
'binddn':targetbinddn,
'bindpw':targetbindpw
},
'lastserver': {
'hostname':'lastserver.foo.com',
'binddn':targetbinddn,
'bindpw':targetbindpw
}
}
并使用以下内容更改for:
for server in consumers.values():
do_something_to_server(server['hostname'], server['binddn'], server['bindpw'])
答案 2 :(得分:1)
听起来你要么想要一本字典字典,要么在你的字典中添加另一个字段,以便在你的伪代码中捕获你面前的名字。
此外,您遇到的主要问题是您的字典语法错误。字典是:
{ 'key': 'value'}
# or
dict(key = 'value')
# not
{'key' = 'value'}
答案 3 :(得分:1)
您可以使用效率更高的namedtuple
类型
from collections import namedtuple
server = namedtuple('server', ('hostname','binddn','bindpw'))
consumers = [
server(
hostname = 'aserver.foo.com',
binddn = masterbinddn,
bindpw = masterbindpw
),
server(
hostname = 'anotherserver.foo.com',
binddn = masterbinddn,
bindpw = masterbindpw
),
server(
hostname = 'athirdserver.foo.com',
binddn = targetbinddn,
bindpw = targetbindpw
),
server(
hostname = 'lastserver.foo.com',
binddn = targetbinddn,
bindpw = targetbindpw
),
]
你的循环变为:
for consumer in consumers:
do_something_to_server(consumer.hostname, consumer.binddn, consumer.bindpw)
甚至:
for consumer in consumers:
do_something_to_server(*consumer)
答案 4 :(得分:0)
您的示例数据结构无效Python:您不能紧跟字典后跟字符串。
但要获得一个简单的词典列表,这将有效:
consumers = ['aserver.foo.com','anotherserver.foo.com',
'thirdserver.foo.com','lastserver.foo.com']
consumer_dict = [{'hostname': consumer, 'binddn': targetbinddn, 'bindpw': targetbindpw}
for consumer in consumers