Home > Net >  How to merge Python dict keys when their values are duplicates?
How to merge Python dict keys when their values are duplicates?

Time:08-14

This question is kind of hard to formulate, but let's say I have a dictionary.

{
   'a': 'hi',
   'b': 'hello',
   'c': 'hi'
}

How can I re-arrange the keys and values to get a dictionary like this:

{
   'a and c': 'hi',
   'b': 'hello'
}

Thank you for your help, I hope I was clear enough...

CodePudding user response:

You can append all the duplicate keys to a list with the value as the key, and than invert the new dict whole creating a string from the new values

d = {'a': 'hi', 'b': 'hello', 'c': 'hi'}

temp_dict = {}
for k, v in d.items():
    temp_dict[v] = temp_dict.get(v, [])   [k]
    # or as suggested in the comments
    # temp_dict.setdefault(v, []).append(k) 

d = {' and '.join(v): k for k, v in temp_dict.items()}
print(d)

Output

{'a and c': 'hi', 'b': 'hello'}

CodePudding user response:

You can use answers from this question to construct a flipped dictionary.

Here is an example:

d = {'a': 'hi', 'b': 'hello', 'c': 'hi'}
flipped = {}

for key, value in d.items():
    if value not in flipped:
        flipped[value] = [key]
    else:
        flipped[value].append(key)
{'hi': ['a', 'c'], 'hello': ['b']}  # flipped

Then you can iterate over unique values of your dictionary, selecting their keys, and joining them with ' and ':

unique_vals = set(d.values())
new_d = {}

for unique_val in unique_vals:
    old_keys = flipped[unique_val]
    new_key = ' and '.join(old_keys)
    new_d[new_key] = unique_val
{'b': 'hello', 'a and c': 'hi'}  # new_d
  • Related