Reputation: 831
Say I have some function which returns a dictionary and I iterate over that function. This will produce a list of dictionaries. I wish to convert this into a dictionary. I am calling my function like this:
x = [_myfunction(element) for element in list_of_elements]
Resulting in say x:
x = [{'one': {'two':'2'}, 'three' : '3'}, {'four':'five', 'six':{'seven':7}}]
and I wish to convert into y:
y = {'one': {'two':'2'}, 'three' : '3', 'four':'five', 'six':{'seven':7}}
Is there a way of calling _myfunction() over the list_of_elements, such that it directly results in y? Maybe with a dictionary comprehension instead of the above list comprehension? Or what the most concise code to turn x into y. (Hopefully without being boring and using a for loop! :-) )
Thanks, labjunky
Upvotes: 2
Views: 142
Reputation: 64398
You can merge dicts using the dict.update method:
y = {}
for element in list_of_elements:
y.update(_myfunction(element))
You can also use a (double-loop) dict-comprehension:
y = {
k:v
for element in list_of_elements
for k,v in _myfunction(element).items()
}
Finally, if you take any of the answers to this question, for merging two dicts (and name it merge_dicts
), you can use reduce
to merge more than two:
dicts = [_myfunction(element) for element in list_of_elements]
y = reduce(merge_dicts, dicts, {})
Either way, in case of repeated dict keys, later keys overwrite earlier ones.
Upvotes: 2