Menu

gitpiper

combine_values python Code Snippet in 2024

dictionaryintermediate

Last Updated: 14 December 2024

Combines two or more dictionaries, creating a list of values for each key.

  • Create a new collections.defaultdict with list as the default value for each key and loop over dicts.
  • Use dict.append() to map the values of the dictionary to keys.
  • Use dict() to convert the collections.defaultdict to a regular dictionary.
from collections import defaultdict def combine_values(*dicts): res = defaultdict(list) for d in dicts: for key in d: res[key].append(d[key]) return dict(res)
d1 = {'a': 1, 'b': 'foo', 'c': 400} d2 = {'a': 3, 'b': 200, 'd': 400} combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}

python snippet similar to combine_values For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️