There is an exercise in the book Python Workout: 50 Ten-minute Exercises that asks to write a function to do the following:
Write a function that takes a list of dicts and returns a single dict that combines all of the keys and values. If a key appears in more than one argument, the value should be a list containing all of the values from the arguments.
Here is my code:
def combine_dicts(dict_list):
combined = {}
for dict_ in dict_list:
for key, value in dict_.items():
if key not in combined.keys():
combined[key] = [value]
else:
combined[key] = combined[key] + [value]
return dict([((key, value[0]) if len(value) == 1 else (key, value)) \
for key, value in combined.items()])
what are some ideas that I can use to improve my code, make it more pythonic?
Example input and outputs:
>>> combine_dicts([{'a': [1, 2]}, {'a':[3]}, {'a': [4, 5]}])
{'a': [[1, 2], [3], [4, 5]]}
>>> combine_dicts([{'a': 1, 'b':2}, {'c':2, 'a':3}])
{'a': [1, 3], 'b': 2, 'c': 2}