How to combine every nth dict element in python list?

Viewed 402

Input:

list1 = [
   {
      "dict_a":"dict_a_values"
   },
   {
      "dict_b":"dict_b_values"
   },
   {
      "dict_c":"dict_c_values"
   },
   {
      "dict_d":"dict_d_values"
   }
]

Assuming n=2, every two elements have to be combined together.

Output:

list1 = [
   {
      "dict_a":"dict_a_values",
      "dict_c":"dict_c_values"
   },
   {
      "dict_b":"dict_b_values",
      "dict_d":"dict_d_values"
   }
]

Ideally, it'd be nicer if the output could look like something as follows with an extra layer of nesting:

[
   {"dict_combined_ac": {
      "dict_a":"dict_a_values",
      "dict_c":"dict_c_values"
   }},
   {"dict_combined_bd": {
      "dict_b":"dict_b_values",
      "dict_d":"dict_d_values"
   }}
]

But since this is really difficult to implement, I'd be more than satisfied with an output looking something similar to the first example. Thanks in advance!

What I've tried so far:

[ ''.join(x) for x in zip(list1[0::2], list1[1::2]) ]

However, I know this doesn't work because I'm working with dict elements and not str elements and when wrapping the lists with str(), every two letters is being combined instead. I'm also unsure of how I can adjust this to be for every n elements instead of just 2.

1 Answers

Given the original list, as in the question, the following should generate the required output:

result_list = list()

n = 2           # number of elements you want in each partition
seen_idx = set()

for i in range(len(list1)):     # iterate over all indices
    if i not in seen_idx:
        curr_idx_list = list()                  # current partition
        for j in range(i, len(list1), n):       # generate indices for a combination partition
            seen_idx.add(j)                     # keep record of seen indices
            curr_idx_list.append(j)             # store indices for current partition

        # At this point we have indices of a partition, now combine
        temp_dict = dict()          # temporary dictionary where we store combined values
        for j in curr_idx_list:     # iterate over indices of current partition
            temp_dict.update(list1[j])
        result_list.append(temp_dict)           # add to result list

print(result_list, '\n')

# Bonus: change result list into list of nested dictionaries
new_res_list = list()

for elem in result_list:    # for each (combined) dictionary in the list, we make new keys
    key_names = list(elem.keys())
    key_names = [e.split('_')[1] for e in key_names]
    new_key = 'dict_combined_' + ''.join(key_names)

    temp_dict = {new_key: elem}
    new_res_list.append(temp_dict)

print(new_res_list, '\n')

The output is as follows:

[{'dict_a': 'dict_a_values', 'dict_c': 'dict_c_values'}, {'dict_b': 'dict_b_values', 'dict_d': 'dict_d_values'}] 

[{'dict_combined_ac': {'dict_a': 'dict_a_values', 'dict_c': 'dict_c_values'}}, {'dict_combined_bd': {'dict_b': 'dict_b_values', 'dict_d': 'dict_d_values'}}]
Related