patternpythonMinor
Merging values with lists as flat-lists
Viewed 0 times
mergingwithflatlistsvalues
Problem
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?
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_dictSolution
Merging many dictionaries
Instead of merging just 2 dictionaries, how about allowing to merge many?
Improving
Improvements:
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_dictImproving
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 mergedImprovements:
- 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?
Code Snippets
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_dictdef 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 mergedContext
StackExchange Code Review Q#60277, answer score: 4
Revisions (0)
No revisions yet.