Python dict.keys以重复形式列出结果

Python dict.keys以重复形式列出结果,python,list,key,Python,List,Key,我有一本字典,使用.keys()将其转换为键列表,然后将键小写并对列表排序,如下所示: dictionary = list() # covert all to lower case for word in self._dict.keys(): dictionary.append(word.lower()) dictionary.sort() print dictionary[:5] class C: def __init__(self): self.a = None

我有一本字典,使用
.keys()
将其转换为键列表,然后将键小写并对列表排序,如下所示:

dictionary = list()
# covert all to lower case
for word in self._dict.keys():
  dictionary.append(word.lower())
dictionary.sort()
print dictionary[:5]
class C:
    def __init__(self):
        self.a = None
        self.A = None
        self.aA = None
        self.Aa = None
        self.AAA = None
        self.aAa = None
打印
[u'a',u'a',u'aa',u'aa',u'aaa']

为什么元素是重复的


更新:愚蠢的我,没想到原来的字典里可能有小写字母。。。纯粹的尴尬

,因为您已将键转换为小写。例如:

'AAA'.lower() == 'aaa'
True
'Aa'.lower() == 'aA'.lower()
True
因此,如果您有这样定义的类:

dictionary = list()
# covert all to lower case
for word in self._dict.keys():
  dictionary.append(word.lower())
dictionary.sort()
print dictionary[:5]
class C:
    def __init__(self):
        self.a = None
        self.A = None
        self.aA = None
        self.Aa = None
        self.AAA = None
        self.aAa = None
然后是它的一个实例:

>>> c = C()
>>> c.__dict__
{'a': None, 'A': None, 'aA': None, 'AAA': None, 'Aa': None, 'aAa': None}
>>> c.__dict__.keys()
['a', 'A', 'aA', 'AAA', 'Aa', 'aAa']
将关键帧转换为小写将导致重复:

>>> sorted(key.lower() for key in c.__dict__.keys())
['a', 'a', 'aa', 'aa', 'aaa', 'aaa']

例如,如果其中一个键是
u'A'
,另一个键是
u'A'
,那么您将从第一个键获得
u'A'
,从第二个键获得
u'A'

字符串区分大小写:

>>> 'AA' == 'aa'
False
字典键也区分大小写,所以将它们全部转换为小写可能会产生重复项。要消除重复项,请使用
set
对象:

>>> list(set(['AAA', 'aaa', 'AAA', 'aaa']))
['aaa', 'AAA']

您不应该使用名称
字典
作为列表…您的代码有效。错误应该在
\u dict
中。你能发布它的样子吗?@JBernardo我同意,但在这种情况下,我正在建立一个拼写词典列表,因此我将其命名为“dictionary”LOLyes,我一生都没有意识到在创建dict变量时,可能会有来自源代码的小写键。。。纯粹的尴尬