2
\$\begingroup\$

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}
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You provide 2 identical example inputs with 2 differing example outputs. Something doesn't add up here. \$\endgroup\$
    – Mast
    Commented Nov 18, 2022 at 22:48
  • \$\begingroup\$ @Mast Sorry my mistake, I fixed the examples. \$\endgroup\$ Commented Nov 19, 2022 at 16:11

1 Answer 1

2
\$\begingroup\$

At first glance your code looks pretty pythonic to me. I would suggest the following changes:

  • when you are adding a new value to an existing key's list, you use list concatenation to create a new list: combined[key] = combined[key] + [value]. What you should do instead is append the new value to the existing list: combined[key].append(value)

  • in the return statement you create a list of tuples using list comprehension which is then converted to a dictionary. Instead you can directly use a dictionary comprehension to create the dictionary more elegantly: return {key : (value[0] if len(value) == 1 else value) for key, value in combined.items()}

The resulting code looks as follows:

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].append(value)
 
     return {
         key : (value[0] if len(value) == 1 else value)
         for key, value in combined.items()
     }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.