3
\$\begingroup\$

I'm merging dictionaries together in series. Each one may/may not have lists as values. I'd like to merge indefinitely and, have the final merged dictionary contain only flat lists as values.

Any advice for how to write this as a single/simpler function?

def merge_dlist(dict_1, dict_2):
    """Merge_dlist accepts dictionaries to be merged."""
    merged_dict = defaultdict(list)
    merged_dict = merge_type(dict_1, merged_dict)
    merged_dict = merge_type(dict_2, merged_dict)
    return merged_dict

def merge_type(dictionary, merged_dict):
"""Merge dictionary keys. Append value items as strings to value list."""
for key, value in dictionary.items():
    if isinstance(value, list):
        for item in value:
            merged_dict[key].append(item)
    if isinstance(value, str):
        merged_dict[key].append(value)
return merged_dict
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Merging many dictionaries

Instead of merging just 2 dictionaries, how about allowing to merge many?

def merge_dlist(*args):
    """Merge_dlist accepts dictionaries to be merged."""
    merged_dict = defaultdict(list)
    for dictionary in args:
        merged_dict = merge_type(dictionary, merged_dict)
    return merged_dict

Improving merge_type like this:

def merge_dictionary(dictionary, merged):
    """Merge dictionary keys. Append value items to value list."""
    for key, value in dictionary.items():
        if isinstance(value, list):
            merged[key].extend(value)
        else:
            merged[key].append(value)
    return merged

Improvements:

  • Naming: "merge_type" is a strange name, I don't know what it means. I think "merge_dictionary" makes more sense.
  • Instead of appending list items one by one with .append, it's better to add all at once using .extend
  • Why limit to string types? Why not append any kind of non-list values in general?
\$\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.