我有一个字典列表,其中特定值重复多次,我想删除重复的值。
我的清单:
te = [ { "Name": "Bala", "phone": "None" }, { "Name": "Bala", "phone": "None" }, { "Name": "Bala", "phone": "None" }, { "Name": "Bala", "phone": "None" } ]
删除重复值的功能:
def removeduplicate(it): seen = set() for x in it: if x not in seen: yield x seen.add(x)
当我调用此函数时,我得到了generator object。
generator object
<generator object removeduplicate at 0x0170B6E8>
当我尝试遍历生成器时,我得到 TypeError: unhashable type: 'dict'
TypeError: unhashable type: 'dict'
有没有办法删除重复的值或遍历生成器
您可以通过字典理解轻松地删除重复键,因为字典不允许重复键,如下所示-
te = [ { "Name": "Bala", "phone": "None" }, { "Name": "Bala", "phone": "None" }, { "Name": "Bala", "phone": "None" }, { "Name": "Bala", "phone": "None" }, { "Name": "Bala1", "phone": "None" } ] unique = { each['Name'] : each for each in te }.values() print unique
输出-
[{'phone': 'None', 'Name': 'Bala1'}, {'phone': 'None', 'Name': 'Bala'}]