[英]Python dict.keys to list results in duplicates
I have a dictionary and using .keys()
to convert into a list of keys then lower case the keys and sort the list, like this: 我有一个字典并使用
.keys()
转换为键列表然后小写键并对列表进行排序,如下所示:
dictionary = list()
# covert all to lower case
for word in self._dict.keys():
dictionary.append(word.lower())
dictionary.sort()
print dictionary[:5]
prints [u'a', u'a', u'aa', u'aa', u'aaa']
打印
[u'a', u'a', u'aa', u'aa', u'aaa']
Why elements are duplicated? 为什么元素重复?
UPDATE: stupid me, didn't think of there might be lower case letters in the original dictionary... pure embarrassment 更新:愚蠢的我,没想到原字典中可能会有小写字母......纯粹的尴尬
Because you've converted the keys to lower case. 因为您已将键转换为小写。 For example:
例如:
'AAA'.lower() == 'aaa'
True
'Aa'.lower() == 'aA'.lower()
True
So, if you had a class defined like this: 所以,如果你有一个像这样定义的类:
class C:
def __init__(self):
self.a = None
self.A = None
self.aA = None
self.Aa = None
self.AAA = None
self.aAa = None
And then an instance of it: 然后是它的一个实例:
>>> 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']
Converting the keys to lower case results in duplicates: 将密钥转换为小写会导致重复:
>>> sorted(key.lower() for key in c.__dict__.keys())
['a', 'a', 'aa', 'aa', 'aaa', 'aaa']
Strings are case sensitive: 字符串区分大小写:
>>> 'AA' == 'aa'
False
Dictionary keys are also case-sensitive, so converting them all to lowercase might give you duplicates. 字典键也区分大小写,因此将它们全部转换为小写可能会给您重复。 To get rid of the duplicates, use a
set
object: 要删除重复项,请使用
set
对象:
>>> list(set(['AAA', 'aaa', 'AAA', 'aaa']))
['aaa', 'AAA']
如果,例如,关键之一是u'A'
另一个按键是u'a'
,那么你会得到u'a'
从第一和u'a'
从第二。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.