Trying to convert list of OrderedDict to Dictionary Key value Python

107 views Asked by At

I need to convert ordereddict to dictionary key value.

 test = [OrderedDict([('key', 'value'),
              ('name', 'A'),
              ('value', '5')]),
 OrderedDict([('key', 'value'),
              ('name', 'B'),
              ('value', '10')]),
 OrderedDict([('key', 'value'),
              ('name', 'C'),
              ('value', '25')])]here


Desired Output:
{'A': '5', 'B': '10', 'C': '25'}
1

There are 1 answers

0
Green Cloak Guy On BEST ANSWER

Your test is essentially a list of dictionaries. Each of those dictionaries has a key 'name', which we want to be the key in our output, and a key 'value', which we want to be the value in our output. So, we can just use a dict comprehension to iterate through the dicts contained by test, and transform each one into a single key-value pair.

output = {od['name']: od['value'] for od in test}
# {'A': '5', 'B': '10', 'C': '25'}

If you wanted the output to also be an OrderedDict, then you could feed a generator comprehension to the constructor:

output_od = OrderedDict((od['name'], od['value']) for od in test)
# OrderedDict([('A', '5'), ('B', '10'), ('C', '25')])