使用字典作为列表

时间:2015-02-10 19:05:37

标签: python

我正在学习python,我正在尝试使用字典(或任何其他方式)来设置“列表字典”,我可以使用for循环进行迭代。

这是我需要循环的数据结构的示例:

name: alert1
id: 12345
name: alert2
id: 54321

我已经使用下面的代码,但我不确定我是采用“推荐”方式,还是代码存在任何重大缺陷:

# Gets arguments
option = (sys.argv[1])

def disable_alert(alert_name,alert_id):
    disable_alert = {'enabled':False,'dampeningCategory':'ONCE'}
    print "Disabling alert %s (ID: %s)" % (alert_name,alert_id)
    req = requests.put(endpoint+'alert/definition/%s' % (alert_id),json.dumps(disable_alert),headers=headers,auth=auth)
    check_status = req.json()['enabled']
    if check_status == False:
        print "Alert %s disabled\n" % alert_name
    else:
        print "Alert %s did not disable\n" % alert_name

alerts = {'name':['ils.txdatasource.dbpool','SEND_PIX_TO_EXTERNAL_HOST_VIA_IFEE','SEND_ShipConfirm_TO_EXTNL_HOST_VIA_IFEE'],'id':['10435','10423','10421']}

if option == "disable":
    count = 0
    for nothing in alerts['name']:
        disable_alert(alerts['name'][count],alerts['id'][count])
        count = count - 1
else:
    print "I don't know that option"

以下是工作代码的示例输出:

$ python jon_alerts.py disable
Disabling alert ils.txdatasource.dbpool (ID: 10435)
Alert ils.txdatasource.dbpool disabled

Disabling alert SEND_PIX_TO_EXTERNAL_HOST_VIA_IFEE (ID: 10423)
Alert SEND_PIX_TO_EXTERNAL_HOST_VIA_IFEE disabled

Disabling alert SEND_ShipConfirm_TO_EXTNL_HOST_VIA_IFEE (ID: 10421)
Alert SEND_ShipConfirm_TO_EXTNL_HOST_VIA_IFEE disabled

1 个答案:

答案 0 :(得分:1)

您可以遍历python词典。我认为更好的方法来构建信息,而不是

alerts = {'names': [some list of names], 'ids': [some list of ids]}

可能就是这样:

alerts = {
    'ils.txdatasource.dbpool': '10435',
    'SEND_PIX_TO_EXTERNAL_HOST_VIA_IFEE': '10423',
    'SEND_ShipConfirm_TO_EXTNL_HOST_VIA_IFEE': '10421',
    'alert4': 'id4',
    ...
}

然后你会像这样迭代:

for name in alerts:
    disable_alert(name, alerts[name])

不需要柜台或类似的东西。通常,如果你发现自己想在python中使用一个计数器,那么实际使用计数器可能比使用计数器更好。

只是为了向您展示如何访问该字典,我只是在python命令行中快速完成了这个:

>>> alerts = {'ils.txdatasource.dbpool': '10435', 'SEND_PIX_TO_EXTERNAL_HOST_VIA_IFEE': '10423', 'SEND_ShipConfirm_TO_EXTNL_HOST_VIA_IFEE': '10421', 'alert4': 'id4'}
>>> for name in alerts:
...     print 'name: {0}, id: {1}'.format(name, alerts[name])
... 
name: ils.txdatasource.dbpool, id: 10435
name: SEND_PIX_TO_EXTERNAL_HOST_VIA_IFEE, id: 10423
name: alert4, id: id4
name: SEND_ShipConfirm_TO_EXTNL_HOST_VIA_IFEE, id: 10421
>>>

请注意,它没有按照我在字典中声明的相同顺序浏览项目。字典是无序的。但是,为了这个用例,您似乎并不需要它们。