2

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

labjunky
  • 831
  • 1
  • 13
  • 22
  • 2
    `y` is a *tuple* of dictionaries, hardly an improvement. Did you want to have *one dictionary* with keys `'one'`, `'three'`, `'four'` and `'six'` instead? – Martijn Pieters Apr 10 '14 at 18:56
  • The `y` you want, is not a dictionary, it's a tuple of 2 elements (2 dictionaries). – Christian Tapia Apr 10 '14 at 18:57
  • If you truly want a single dictionary, you'll have to tell us what you want to do when one key appears in two (or more) dictionaries. – Dunno Apr 10 '14 at 19:00
  • 1
    opps yes you are right. I have corrected it. In the case of identical keys, its ok to overwrite. – labjunky Apr 10 '14 at 19:11

1 Answers1

2

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.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153