我有这样的字典:
dct = {'one': 'value',
'two': ['value1','value2','value1'],
'three':['otherValue1','otherValue2','otherValue1'],
'dontCareAboutThisKey':'debug'}
我需要从列表中删除重复的值。我写了一个函数来做到这一点:
no_dups = {}
for keys in dct:
if isinstance(dct[keys], list) and keys != 'dontCareAboutThisKey':
for value in dct[keys]:
if value not in no_dups.values():
no_dups[keys].append(value)
else:
no_dups[keys] = dct[keys]
我正在检查当前键的值是否为列表。如果不是,则只需将“复制”键复制到no_dups
字典。如果它是一个列表而不是我不关心的密钥(肯定没有重复) - 它应检查no_dups.values()
中是否已存在当前值并将其附加到当前密钥。问题是我收到了错误:
KeyError: 'two:'
我知道这是因为我正在尝试为非现有密钥添加一个值,但我不知道如何处理这个并让它工作。
答案 0 :(得分:3)
我认为处理添加密钥和同时添加密钥的最佳方法是使用dicts' setdefault()
方法:
no_dups.setdefault(keys,[]).append(value)
但不是这样,你可以用这样更简洁的方式做到这一点:
#remove duplicates
no_dups = {k:list(set(v)) if isinstance(v, list) and k != 'dontCareAboutThisKey' else v
for k,v in dct.items()} # or dct.iteritems() if using python2.x
对于通过if
测试的键值组合,该hack会将列表转换为集合(删除重复项),然后再次在列表中。对于其他键值组合,它将保持原样。
答案 1 :(得分:2)
dct = {'one': 'value',
'two': ['value1','value2','value1'],
'three':['otherValue1','otherValue2','otherValue1'],
'dontCareAboutThisKey':'debug'}
set(dct)
会返回set
,这是一个没有重复的列表:
for key, value in dct.items():
if not isinstance(value, basestring):
dct[key] = set(value)
如果您需要新词典,可以这样做:
new_dct = {}
for key, value in dct.items():
if not isinstance(value, basestring):
new_dct[key] = set(value)
else:
new_dct[key] = value
答案 2 :(得分:1)
如果您想删除重复项,只需使用set()函数更改您要设置的列表:
https://docs.python.org/2/tutorial/datastructures.html#sets
它会自动为您提供唯一的设置,然后您可以随时将其更改回列表。