Instabrite Instabrite -4 years ago 164
Python Question

Converting name-value pair into Python dictionary

I have a long list of name-value pairs in Python 3 that represent a single row from a database. Since the number of attributes is fairly large per row, I'm wondering if there is a faster or more pythonic way to convert this into a dict than the following:

name_value_pairs = [{'Name':'id', 'Value':1}, {'Name':'age', 'Value':22}]
for pair in name_value_pairs:
result[pair['Name']] = pair['Value']

Answer Source

Use a dictionary comprehension:

result = dict( (item['Name'], item['Value']) for item in name_value_pairs)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download