1

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samuel
  • 3,631
  • 5
  • 37
  • 71

3 Answers3

2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dskrypa
  • 1,004
  • 2
  • 5
  • 17
1

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})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pylos
  • 102
  • 8
1

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'>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arifa Chan
  • 947
  • 2
  • 6
  • 23