简体   繁体   English

当 Python 字典键的值重复时,如何合并它们?

[英]How to merge Python dict keys when their values are duplicates?

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...谢谢你的帮助,我希望我足够清楚......

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您可以 append 将所有重复键添加到一个以该值作为键的列表中,然后反转整个新dict ,从新值创建一个字符串

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 Output

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM