How to convert a list of dictionaries to a Bunch object

Question:

I have a list of the following dictionaries:

[{'Key': 'tag-key-0', 'Value': 'value-0'},
 {'Key': 'tag-key-1', 'Value': 'value-1'},
 {'Key': 'tag-key-2', 'Value': 'value-2'},
 {'Key': 'tag-key-3', 'Value': 'value-3'},
 {'Key': 'tag-key-4', 'Value': 'value-4'}]

Is there an elegant way to convert it to a Bunch object?

Bunch(tag-key-0='value-0', tag-key-1='value-1', tag-key-2='value-2', tag-key-3='value-3', tag-key-4='value-4')

My current solution is:

from bunch import Bunch

tags_dict = {}
for tag in actual_tags:
    tags_dict[tag['Key']] = tag['Value']

Bunch.fromDict(tags_dict)
Asked By: Samuel

||

Answers:

Import:

from bunch import Bunch

Option 1:

b = Bunch({t['Key']:t['Value'] for t in actual_tags})

Option 2:

b = Bunch.fromDict({t['Key']:t['Value'] for t in actual_tags})
Answered By: pylos

Unless you are using a version of Bunch that is different than the one that you get via pip install bunch, the Bunch class has no from_dict classmethod.

Using Bunch(tags_dict) appears to work:

>>> from bunch import Bunch

>>> actual_tags = [{'Key': 'tag-key-0', 'Value': 'value-0'},
...  {'Key': 'tag-key-1', 'Value': 'value-1'},
...  {'Key': 'tag-key-2', 'Value': 'value-2'},
...  {'Key': 'tag-key-3', 'Value': 'value-3'},
...  {'Key': 'tag-key-4', 'Value': 'value-4'}]

>>> tags_dict = {tag['Key']: tag['Value'] for tag in actual_tags}

>>> print(Bunch(tags_dict))
tag-key-0: value-0
tag-key-1: value-1
tag-key-2: value-2
tag-key-3: value-3
tag-key-4: value-4

One thing to note: Bunch does not appear to be actively maintained – its last commit was over 10 years ago, and it does not seem to be fully compatible with Python 3. AttrDict appears to be more recent, but it is also inactive.

Answered By: dskrypa

Use map of Bunch.values() from actual_tags:

actual_tags = [{'Key': 'tag-key-0', 'Value': 'value-0'},
               {'Key': 'tag-key-1', 'Value': 'value-1'},
               {'Key': 'tag-key-2', 'Value': 'value-2'},
               {'Key': 'tag-key-3', 'Value': 'value-3'},
               {'Key': 'tag-key-4', 'Value': 'value-4'}]

from bunch import Bunch

tags_dict = Bunch(map(Bunch.values, actual_tags))

print(tags_dict)
print(type(tags_dict))

Output:

tag-key-0: value-0
tag-key-1: value-1
tag-key-2: value-2
tag-key-3: value-3
tag-key-4: value-4

<class 'bunch.Bunch'>
Answered By: Arifa Chan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.