python - Assigning Elements/Keys to a Dictionary -
im assigning number of elements dictionary via list based elements.
such :
z = mylist query_dict = {"hostname":z[0],"ttl":z[1],"class":z[2],"type":z[3],"details":z[4]}
however wondered if there more elegant approach this, such way can assign variables list :
a,b,c,d,e = z
thanks,
>>> 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}
how works:
the dict
class has initialization method takes iterable:
| dict(iterable) -> new dictionary initialized if via: | d = {} | k, v in iterable: | d[k] = v
where iterable
contains/yields key value pairs in form (key,value)
. using zip
can generate these pairs:
>>> zip(terms,z) [('hostname', 1), ('ttl', 2), ('class', 3), ('type', 4), ('details', 5)]
hence feed in iterable constructor resulting in our desired dictionary.
Comments
Post a Comment