繁体   English   中英

Python:比较字典键

[英]Python: Compare Dictionary Keys

我有一本字典,其中有两个标识一组数据的键。 这些键当前存储为排列(因此,即使它们具有相同的数据,也存在键1,2和键2,1)。

我想消除重复的值。

例如:

我有这个(其中key1,key2重复为key2,key1)

dict = {'key1, key2':1, 'key2, key3':2, 'key2, key1':1}

我想要

dict = {'key1, key2':1,'key2, key3':2}

有什么想法吗?

dict((", ".join(sorted(k.split(", "))), v) for k, v in d.iteritems())是否正在寻找您想要的?

首先,切勿使用dict作为变量名,它会掩盖内置函数。

您可以将任何不可变的对象用作字典键,因此,像frozenset这样的集合可能比字符串更适合您的用例:

>>> data = {'key1, key2':1, 'key2, key3':2, 'key2, key1':1}
>>> new_data = {
  frozenset(item.strip() for item in key.split(',')): val 
  for key, val in data.items()
}
>>> new_data

{frozenset({'key1', 'key2'}): 1, 
 frozenset({'key2', 'key3'}): 2}

如果您确实需要键为字符串:

>>> {", ".join(key): val for key, val in new_data.items()}

{'key2, key1': 1, 'key3, key2': 2}

[更新]

按照Achim的建议使用已排序的元组:

>>> new_data = {
  tuple(sorted(item.strip() for item in key.split(','))): val
  for key, val in data.items()
}
>>> new_data

{('key1', 'key2'): 1, ('key2', 'key3'): 2}

>>> {", ".join(key): val for key, val in new_data.items()}

{'key1, key2': 1, 'key2, key3': 2}

暂无
暂无

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

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