【问题标题】:Probems with merging same values for different keys in dictionary为字典中的不同键合并相同值的问题
【发布时间】:2019-08-18 01:29:29
【问题描述】:

我有很多坐标,为此我创建了一个大字典,其中各个键可能具有相同的值列表。我想将这些键与相同的值列表合并,以计算有多少键具有给定的值列表。我已经设法合并它们,但由于某种原因,有些值被颠倒了,因此没有正确合并。

到目前为止,我已经尝试使用合并的键作为元组创建一个新字典,并将值保存为列表。此外,我只保留那些具有两个或多个键的值列表。

我的开始词典

start_dict = {
    'Key1': [243928620, 243938319],
    'Key2': [243935130, 243935973],
    'Key3': [243928620, 243938319],
    'Key4': [243928628, 243938315],
    'Key5': [243928628, 243938315],
    'Key6': [243930418, 243933130, 243933141]
}

其中 Key1 和 3 具有相同的值列表,Key4 和 5 相同。 所以我用

合并了它们
from collections import defaultdict
New_dict= defaultdict(list)
for k, v in sorted(start_dict.items()):
    New_dict[tuple(v)].append(k)

final_dict = {tuple(v):set(k) for k, v in New_dict.items()}

预期结果是

{(‘Key1’,’Key2’): {243928620, 243938319}, (‘Key4’,’Key5’): {243928628, 243938315}}

但由于某种原因,它最终变成了

{(‘Key1’,’Key2’): {243928620, 243938319}, (‘Key4’,’Key5’): {243938315,243928628}}

单个列表中的值在哪里切换,这是一个问题,因为坐标的顺序很重要。

当然,实际数据集更大,合并适用于 49/50 的键和值对列表。

感谢您的宝贵时间和建议。

【问题讨论】:

  • 您正在使用 set() ,因此集合的内容按数字顺序排列。您需要一种不同的方法来合并它们。

标签: python sorting dictionary merge


【解决方案1】:

使用中间字典的想法是正确的,但是这个字典的键应该是原字典的

new_dict = defaultdict(list)
for k, v in sorted(start_dict.items()):
    new_dict[tuple(v)].append(k)

final_dict = { tuple(v): list(k) for k, v in new_dict.items() if len(v) > 1 }

无需使用set,因为我们不关心列表本身中值的唯一性。

输出:

{('Key1', 'Key3'): [243928620, 243938319], ('Key4', 'Key5'): [243928628, 243938315]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2015-08-25
    • 2021-10-21
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多