How to convert python tuple to dict

Sometimes you might need to convert tuple (or list) to dict object to make it more readable. After all l['product_id'] is more readable than l[4]. For this example I will use following sample data:

#create sample keys for our dict
keys = ['id','user_id','user_age','product_id','product_weight']
#create sample data
l = list()
for i in range(1,10):
    l.append((1*i,2*i,3*i,4*i,5*i))

print l

# [(1, 2, 3, 4, 5),
#  (2, 4, 6, 8, 10),
#  (3, 6, 9, 12, 15),
#  (4, 8, 12, 16, 20),
#  (5, 10, 15, 20, 25),
#  (6, 12, 18, 24, 30),
#  (7, 14, 21, 28, 35),
#  (8, 16, 24, 32, 40),
#  (9, 18, 27, 36, 45)]

For start, I have a list of tuples and I would like to have a dictionary. To archive this first I need to zip two tuples together

zip(keys,l[2])

# [('id', 3),
#  ('user_id', 6),
#  ('user_age', 9),
#  ('product_id', 12),
#  ('product_weight', 15)]

if we send this to dict constructor, we will have first values of tuples as keys and second value of tuples as values and we will achieve our goal.

dict(zip(keys,l[2]))

# {'id': 3, 'product_id': 12, 'product_weight': 15, 'user_age': 9, 'user_id': 6}

This is how we can convert tuple to dict. If we need to convert whole list of tuples to list of dictionaries

[dict(zip(keys,row)) for row in l]

#[{'id': 1, 'product_id': 4, 'product_weight': 5, 'user_age': 3, 'user_id': 2},
# {'id': 2, 'product_id': 8, 'product_weight': 10, 'user_age': 6, 'user_id': 4},
# {'id': 3, 'product_id': 12, 'product_weight': 15, 'user_age': 9, 'user_id': 6},
# {'id': 4, 'product_id': 16, 'product_weight': 20, 'user_age': 12, 'user_id': 8},
# {'id': 5, 'product_id': 20, 'product_weight': 25, 'user_age': 15, 'user_id': 10},
# {'id': 6, 'product_id': 24, 'product_weight': 30, 'user_age': 18, 'user_id': 12},
# {'id': 7, 'product_id': 28, 'product_weight': 35, 'user_age': 21, 'user_id': 14},
# {'id': 8, 'product_id': 32, 'product_weight': 40, 'user_age': 24, 'user_id': 16},
# {'id': 9, 'product_id': 36, 'product_weight': 45, 'user_age': 27, 'user_id': 18}]

This technique is quite useful to convert query results to more meaningful format.

blog comments powered by Disqus