我想从我的字典里收到所有二阶键的列表。在
myDict = {
u'A': {'1998': u'ATLANTA'},
u'B': {'1999': u'MANNHEIM'},
u'C': {'2000': u'BERLIN'},
u'D': {'1998': u'CHICAGO', '1999': u'PRINCETON'},
u'E': {'2000': u'LOUISIANA'},
u'F': {'1998': u'NEW YORK', '1999': u'NEW YORK'}
}
我知道
^{pr2}$其中uniqfy()
来自http://www.peterbe.com/plog/uniqifiers-benchmark:
def uniqfy(seq, idfun=None):
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
一切都按预期工作(即years
是['1998', '2000', '1999']
),但是我确信一定有更好/更短的方法来获取嵌套字典的所有键的列表。在
你可以使用集合理解:
如果您只需要一个list对象,可以使用
^{pr2}$list()
将set
转换为list。在编辑:我更喜欢@Kasra的回答:)
相关问题 更多 >
编程相关推荐