Home > Back-end >  How to convert list of dictionaries to Bunch object
How to convert list of dictionaries to Bunch object

Time:12-21

I have list of 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 elegant way to convert it to 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)

CodePudding user response:

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'>

CodePudding user response:

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})

CodePudding user response:

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.

  • Related