【问题标题】:Merge Keys by common value from the same dictionary通过同一字典中的公共值合并键
【发布时间】:2017-11-07 14:08:45
【问题描述】:

假设我有一本包含以下内容的字典:

myDict = {'A':[1,2], 'B': [4,5], 'C': [1,2]}

我想创建一个新字典 merged,它通过具有相似值的键合并,所以我的 merged 将是:

merged ={['A', 'C']:[1:2], 'B':[4,5]} 

我已尝试使用此thread 中建议的方法,但无法复制我需要的方法。

有什么建议吗?

【问题讨论】:

  • 我已经对我的原始答案进行了编辑,以使您得到几乎您所要求的内容,但代码一团糟。

标签: python-3.x dictionary merge key


【解决方案1】:

你所要求的是不可能的。您在假设字典中的键使用可变列表。由于无法对可变数据进行哈希处理,因此您不能将它们用作字典键。

编辑,我已经按照你的要求去做了,除了这里的键都是元组。这段代码很乱,但你可以清理它。

myDict = {'A':[1,2],
          'B': [4,5],
          'C': [1,2],
          'D': [1, 2],
          }


myDict2 = {k: tuple(v) for k, v in myDict.items()}
print(myDict2) #turn all vlaues into hasable tuples

#make set of unique keys
unique = {tuple(v) for v in myDict.values()}
print(unique) #{(1, 2), (4, 5)}

"""
iterate over each value and make a temp shared_keys list tracking for which
keys the values are found. Add the new key, vlaue pairs into a new
dictionary"""
new_dict = {}
for value in unique:
    shared_keys = []
    for key in myDict:
        if tuple(myDict[key]) == value:
            shared_keys.append(key)
    new_dict[tuple(shared_keys)] = value
print(new_dict) #{('A', 'C'): (1, 2), ('B',): (4, 5)}

#change the values back into mutable lists from tuples
final_dict = {k: list(v) for k, v in new_dict.items()}
print(final_dict)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多