2

Im currently assigning a number of elements to a dictionary via list based elements.

Such as :

z = mylist
query_dict = {"HOSTNAME":z[0],"TTL":z[1],"CLASS":z[2],"TYPE":z[3],"DETAILS":z[4]}

However I wondered if there is a slightly more elegant approach to this, such as the way you can assign variables from a list :

a,b,c,d,e = z

Thanks,

4

3 回答 3

3
>>> terms = ["HOSTNAME","TTL","CLASS","TYPE","DETAILS"]
>>> z = [1,2,3,4,5]
>>> dict(zip(terms,z))
{'HOSTNAME': 1, 'TYPE': 4, 'CLASS': 3, 'DETAILS': 5, 'TTL': 2}

这是如何工作的:

该类dict有一个初始化方法,它需要一个可迭代的:

 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v

其中iterable包含/产生表单中的键值对(key,value)。使用zip我们可以生成这些对:

>>> zip(terms,z)
[('HOSTNAME', 1), ('TTL', 2), ('CLASS', 3), ('TYPE', 4), ('DETAILS', 5)]

因此,我们将这个可迭代对象提供给构造函数,从而得到我们想要的字典。

于 2013-05-20T05:56:55.553 回答
2

你可以zip在这里使用:

>>> keys = ['HOSTNAME','TTL', 'CLASS', 'TYPE', 'DETAILS']
>>> z = range(5)
>>> dict(zip(keys,z))
{'CLASS': 2, 'TYPE': 3, 'DETAILS': 4, 'TTL': 1, 'HOSTNAME': 0}

这里zip返回包含同一索引上的元素对的元组列表:

>>> zip(keys,z)
[('HOSTNAME', 0), ('TTL', 1), ('CLASS', 2), ('TYPE', 3), ('DETAILS', 4)]

并且dict()可以将此列表转换为dict

>>> print dict.__doc__
dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
        d[k] = v
于 2013-05-20T05:56:46.637 回答
1

如果我很好地理解了您的问题,您可以这样做:

fields = ["HOSTNAME", "TTL", "CLASS", "TYPE", "DETAILS"]
query_dict = dict(zip(fields, z))
于 2013-05-20T05:57:37.527 回答