Reputation: 359
I have a list of dictionaries that I need to transform:
my_dictionary = {}
my_array = [{'first': 'this'}, {'second': 'this'}]
What I want is to key my_dictionary
, and then have sub-dictionaries that are equal to the items in my_array
, like so:
my_dictionary = {'red' : {'first': 'this', 'second' : 'this'}}
What I had, in theory was:
for i in my_array:
my_dictionary['red'] = dict(i.items())
but I'm getting an error of:
TypeError: 'dict' object is not callable
I'm realizing though, it's probably because after the first iteration, I'm not creating a dictionary, I'm simply adding to it. Is there a way for me to pull the key from each item in my_array
so that I can specify it more like:
for i in my_array:
my_dictionary['red'][key_from_item_in_my_array] = my_array[key_from_item_in_my_array]
but I'm not sure how to do that.
Upvotes: 0
Views: 176
Reputation: 387
Seems like you want to merge the dictionaries array into a single dictionary and then put that dictionary in another one. The merge is easy:
new_dict = {}
for i in my_array:
new_dict.update(i)
Now you can put your merged dictionary into your second one:
my_dictionary = {}
my_dictionary["red"] = new_dict
This produces:
my_dictionary = {'red': {'first': 'this', 'second': 'this'}}
Upvotes: 3