Home > Software design >  how to combine keys of a dictionary when the values are the same?
how to combine keys of a dictionary when the values are the same?

Time:05-21

I am trying to combine the keys of a dictionary when the values are the same as below,I am trying as below it only prints the values of the dictionary, any guidance how to fix this?

final_BATS_container_id_list = [
    {'Rome_Nightly': ['15715489']},
    {'Rome': ['15715490']},
    {'Italy': ['15715491']},
    {'Paris': ['15715491']},
    {'France': ['15715491']},
    {'Italy_Escape': ['15715493']},
    {'Paris_Escape': ['15715493']},
    {'France_Escape': ['15715493']}]

new_key = ''

for BATS_container_id_dict in final_BATS_container_id_list:
    for key,value in BATS_container_id_dict.items():
        print('key %s => value %s'%(key,value))

Expected output:-

[{'Rome_Nightly': ['15715489']},
 {'Rome': ['15715490']},
 {'Italy/Paris/France': ['15715491']},
 {'Italy_Escape/Paris_Escape/France_Escape': ['15715493']}]

CodePudding user response:

You can use a defaultdict to invert the key/value relationship and accumulate the keys that are associated with values. Then a simple list comprehension will make the desired list of dicts for you:

from collections import defaultdict

l = [
    {'Rome_Nightly': ['15715489']},
    {'Rome': ['15715490']},
    {'Italy': ['15715491']},
    {'Paris': ['15715491']},
    {'France': ['15715491']},
    {'Italy_Escape': ['15715493']},
    {'Paris_Escape': ['15715493']},
    {'France_Escape': ['15715493']}]

groups = defaultdict(list)

for d in l:
    for k, v in d.items():
        groups[v[0]].append(k)

result = [{'/'.join(v): [k]} for k, v in groups.items()]

Giving you a result of:

[{'Rome_Nightly': ['15715489']},
 {'Rome': ['15715490']},
 {'Italy/Paris/France': ['15715491']},
 {'Italy_Escape/Paris_Escape/France_Escape': ['15715493']}]

CodePudding user response:

final_BATS_container_id_list =  [
    {'Rome_Nightly': ['15715489']}, 
    {'Rome': ['15715490']}, 
    {'Italy': ['15715491']}, 
    {'Paris': ['15715491']}, 
    {'France': ['15715491']}, 
    {'Italy_Escape': ['15715493']}, 
    {'Paris_Escape': ['15715493']}, 
    {'France_Escape': ['15715493']}
]

value_map = {}
for item in final_BATS_container_id_list:
    for key, value in item.items():
        first = value[0] # eg. ['15715493'][0]. caution: index out of bounds
        vv = value_map.get(first, [])
        vv.append(key)
        value_map[first] = vv

result = []
for key in value_map.keys():
    joined = '/'.join(value_map[key]) # eg. Italy/Paris/France
    result.append({joined: [key]})

print(result)
  • Related